2009-01-03 79 views
6

是否可以从新的TcpClient中检索底层主机名/端口?您可以从System.Net.Sockets.TcpClient中检索主机名和端口吗?

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

我在client.Client(一System.Net.Socket)周围进行路由,但在那里找不到任何东西了两种。有任何想法吗?

谢谢大家。

回答

13

未经检验的,但我会尝试以下方法:

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的查找,但你特别要求的主机名。

相关问题