是否可以从新的TcpClient检索底层主机名/端口?
TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpClient client = listener.AcceptTcpClient();
// get the hostname
// get the port
我已经在client.Client
(System.Net.Socket
)中绕过,但在那里找不到任何东西。有什么想法吗?
谢谢大家。
答案 0 :(得分:14)
未经测试,但我会尝试以下方法:
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查找,但您明确要求提供主机名。