Introduction
From time to time I need to obtain a TCP clients IP Address while working with a TCP server. I normally forget how to do this and as it is just a one liner — Google doesn't really have any straight forward examples — so I decided to post it here!
Using the Code
Using the code is as easy as taking the example and modifying it to work with your code. The below example will start a TCPServer on port 2000 and once a client has connected, it will send the clients IP Address back to the client.
using System.Net.Sockets;
static NetworkStream stream;
static TcpClient client;
static TcpListener server;
static int port = 2000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
client = server.AcceptTcpClient();
string clientIPAddress = "Your Ip Address is: " + IPAddress.Parse(((
IPEndPoint)client.Client.RemoteEndPoint).Address.ToString()));
stream = client.GetStream();
if (client.Connected) {
Byte[] data = System.Text.Encoding.ASCII.GetBytes(clientIPAddress);
stream.Write(data, 0, data.Length);
}
...a
Points of Interest
For futher reading please make sure to investigate multi-threaded and async TCP client/servers!
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here