你能从System.Net.Sockets.TcpClient中获取主机名和端口吗?

7

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

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

我已经在client.Client(一个System.Net.Socket)中进行了查找,但是也没有发现任何有用的信息。您有什么想法吗?
谢谢大家。
1个回答

15

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

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查找,但你明确要求了一个主机名。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接