是否可以从新的 TcpClient 检索底层主机名/端口?
TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpClient client = listener.AcceptTcpClient();
// get the hostname
// get the port
我在 client.Client
(一个 System.Net.Socket
)中转了一圈,但也找不到任何东西。有什么想法吗?
谢谢大家。
最佳答案
未经测试,但我会尝试以下操作:
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;
如果您可以使用 IP 地址,我会跳过反向 DNS 查找,但您特别要求提供主机名。
关于c# - 您可以从 System.Net.Sockets.TcpClient 检索主机名和端口吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/409906/