【问题标题】:How can I test a TCP connection to a server with C# given the server's IP address and port?给定服务器的 IP 地址和端口,如何使用 C# 测试与服务器的 TCP 连接?
【发布时间】:2010-09-13 06:59:04
【问题描述】:

我如何以编程方式确定我是否可以使用 C# 访问具有给定 IP 地址和端口的服务器 (TCP)?

【问题讨论】:

  • 有必要澄清一下。 “访问”是什么意思?您是否尝试连接到目标机器上的特定端口?
  • 我已将问题更新为更具体(给定 IP+端口的 TCP 访问)

标签: c# networking


【解决方案1】:

您可以使用 Ping 类(.NET 2.0 及更高版本)

平 x = 新平(); PingReply 回复 = x.Send(IPAddress.Parse("127.0.0.1")); 如果(回复.Status == IPStatus.Success) Console.WriteLine("地址可访问");

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

【讨论】:

【解决方案2】:

假设您的意思是通过 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

【讨论】:

  • 声明时创建的 IP 实例将永远不会被使用,因为它会立即作为 out 参数传递,该参数将始终在调用的方法中被替换。所以我会把实例化排除在外。但是你不能不将 IP.TryParse 更改为 IPAddress.TryParse (这是一个静态方法)。所以我也会改变它。
  • 将 IP[0] 更改为仅 IP
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    应该这样做

    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;
    }
    

    【讨论】:

    • 你在哪里定义套接字?这段代码 sn-p 不完整。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多