C# 你能从 System.Net.Sockets.TcpClient 中检索主机名和端口吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/409906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you retrieve the hostname and port from a System.Net.Sockets.TcpClient?
提问by Samir Talwar
Is it possible to retrieve the underlying hostname/port from a new TcpClient?
是否可以从新的 TcpClient 检索底层主机名/端口?
TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpClient client = listener.AcceptTcpClient();
// get the hostname
// get the port
I've routed around in client.Client(a System.Net.Socket), but can't find anything out in there either. Any ideas?
我在client.Client(a System.Net.Socket)中转了一圈,但在那里也找不到任何东西。有任何想法吗?
Thanks all.
谢谢大家。
采纳答案by Rasmus Faber
Untested, but I would try the following:
未经测试,但我会尝试以下操作:
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;
If you can make do with the IPAddress, I would skip the reverse DNS-lookup, but you specifically asked for a hostname.
如果您可以使用 IPAddress,我会跳过反向 DNS 查找,但您特别要求提供主机名。

