【问题标题】:Can you retrieve the hostname and port from a System.Net.Sockets.TcpClient?您可以从 System.Net.Sockets.TcpClient 检索主机名和端口吗?
【发布时间】:2009-01-03 21:41:58
【问题描述】:

是否可以从新的 TcpClient 检索底层主机名/端口?

TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpClient client = listener.AcceptTcpClient();
// get the hostname
// get the port

我在client.ClientSystem.Net.Socket)中转了一圈,但也找不到任何东西。有什么想法吗?

谢谢大家。

【问题讨论】:

    标签: c# networking


    【解决方案1】:

    未经测试,但我会尝试以下方法:

    TcpListener listener = new TcpListener(IPAddress.Any, port);
    TcpClient client = listener.AcceptTcpClient();
    
    IPEndPoint endPoint = (IPEndPoint) client.Client.RemoteEndPoint;
    // .. or LocalEndPoint - depending on which end you want to identify
    
    IPAddress ipAddress = endPoint.Address;
    
    // get the hostname
    IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
    string hostName = hostEntry.HostName;
    
    // get the port
    int port = endPoint.Port;
    

    如果您可以使用 IPAddress,我会跳过反向 DNS 查找,但您特别要求提供主机名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2014-01-12
      • 2019-04-10
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      相关资源
      最近更新 更多