Click here to Skip to main content
Licence 
First Posted 21 Sep 2007
Views 26,933
Bookmarked 16 times

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

By | 21 Sep 2007 | Article
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!

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

About the Author

Dean van Rooyen



Unknown

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralThis isnt an article, it belongs on a Post-It note Pinmemberleppie6:37 21 Sep '07  
GeneralRe: This isnt an article, it belongs on a Post-It note PinmemberWillemM6:47 21 Sep '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 21 Sep 2007
Article Copyright 2007 by Dean van Rooyen
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid