65.9K
CodeProject is changing. Read more.
Home

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

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.04/5 (12 votes)

Sep 21, 2007

viewsIcon

87336

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.

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!