2009-01-03 37 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的查找,但你特別要求的主機名。

相關問題