Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

networking

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.

like image 780
Samir Talwar Avatar asked Jan 03 '09 21:01

Samir Talwar


People also ask

What is system net sockets TcpClient?

The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode. In order for TcpClient to connect and exchange data, a TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests.

How do I listen to a port in C#?

SIP server, and client-program. The SIP server may use port 5010 to listen and establish multiple connections. The client connects from his pc to the server via port 5010. When a packet is received on that port, an event must be triggered on the client PC.

What is TcpListener in C#?

The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a TcpClient or a Socket to connect with a TcpListener. Create a TcpListener using an IPEndPoint, a Local IP address and port number, or just a port number.

What is a TcpListener?

A TCP listener provides TCP server socket support at a specific port within the node. The socket will accept connections and receive messages from a TCP client application. The TCP client application will send messages to the TCP listener in an XML format and ASCII delimited messages.


1 Answers

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.

like image 58
Rasmus Faber Avatar answered Oct 05 '22 23:10

Rasmus Faber