Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Get a TCPServer's Connected Client's IP Address in C#

1.04/5 (18 votes)
21 Sep 2007 2  
An article on getting tcpip client address on the server machine
Screenshot - img.jpg

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.

C#
using System.Net.Sockets;

static NetworkStream stream;
static TcpClient client; 
static TcpListener server;
static int port = 2000;

// setup tcp server
IPAddress localAddr = IPAddress.Parse("127.0.0.1"); 
server = new TcpListener(localAddr, port);
server.Start(); 
client = server.AcceptTcpClient();

//Get the client ip address
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);
}
//close sockets and clean up code
...a

Points of Interest

For futher reading please make sure to investigate multi-threaded and async TCP client/servers!

License

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