在给定服务器的IP地址的情况下,如何使用C#测试与服务器的连接?

如何以编程方式确定是否可以使用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/en-us/library/4xzx2d41.aspx?ppud = 4

您可以使用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(“地址可访问”);

您可能希望在生产系统中使用异步方法来允许取消等。

声明字符串地址和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; }