Samir Talwar
Samir Talwar

Reputation: 14330

Can you retrieve the hostname and port from a System.Net.Sockets.TcpClient?

Is it possible to retrieve the underlying hostname/port from a new 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?

Thanks all.

Upvotes: 7

Views: 17393

Answers (1)

Rasmus Faber
Rasmus Faber

Reputation: 49677

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.

Upvotes: 15

Related Questions