给定服务器的IP地址,如何使用C#测试与服务器的连接?
时间:2020-03-06 14:45:16 来源:igfitidea点击:
如何以编程方式确定是否可以使用C#访问具有给定IP地址的服务器?
解决方案
假设意思是通过TCP套接字:
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
有关更多信息:http://msdn.microsoft.com/zh-cn/library/4xzx2d41.aspx?ppud=4
声明字符串地址和int端口,我们就可以通过TcpClient类进行连接了。
System.Net.Sockets.TcpClient client = new TcpClient();
try
{
client.Connect(address, port);
Console.WriteLine("Connection open, host active");
} catch (SocketException ex)
{
Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
}
finally
{
client.Close();
}
这应该做
bool ssl;
ssl = false;
int maxWaitMillisec;
maxWaitMillisec = 20000;
int port = 555;
success = socket.Connect("Your ip address",port,ssl,maxWaitMillisec);
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}
我们可以使用Ping类(.net 2.0及更高版本)
Ping x = new Ping();
PingReply reply = x.Send(IPAddress.Parse("127.0.0.1"));
if(reply.Status == IPStatus.Success)
Console.WriteLine("Address is accessible");
我们可能想在生产系统中使用异步方法来允许取消等操作。

