Click here to Skip to main content

How to get the clients IP address using TcpClient in Managed C++

<!-- Add the rest of your HTML here -->


In managed C++ using sockets, Microsoft is giving you a whole set of new tools to use Sockets. So you don't have to create a class to handle Client and Server communications. These classes are TcpListener for the server and TcpClient .

TcpListener * pTcpListener;
TcpListener = new TcpListener(80);
TcpClient * pTcpClient; 
pTcpClient = m_TcpListener->AcceptTcpClient();

This opens port 80 and listens for connections. When a client connects to port 80, the function AcceptTcpClient() returns with a TcpClient class.

Those two classes together are very powerful. You should create a thread to use the TcpClient and wait again to accept another client.

The problem I had is I need it to get the IP address of the Client. I couldn't find the way to get it from the TcpClient, even after I get the Stream like this:

 NetworkStream * networkStream = pTcpClient->GetStream();
networkStream->Read(bytes, 0, (int) pTcpClient->ReceiveBufferSize);

Now that I had a NetworkStream I thought I could get the IP address, well I was wrong again. networkStream->getSocket() is a private member of the class NetworkStream.

So, to resolve this problem I had to create a derived class from NetworkStream:

#pragma once

__gc class MyNetworkStream : public NetworkStream
	MyNetworkStream(void) : NetworkStream(0) { };
	MyNetworkStream(System::Net::Sockets::Socket * s) : NetworkStream(s) { };
	System::Net::Sockets::Socket * get_MySocket();
	String * get_IPAddress(void);

//MyNetworkStream.cpp file
#using <System.dll>
#using <mscorlib.dll>
using System::Net::Sockets::NetworkStream;
using System::String;

#include "myNetworkStream.h"

System::Net::Sockets::Socket * MyNetworkStream::get_MySocket()

String * MyNetworkStream::get_IPAddress(void)
	System::Net::Sockets::Socket *soc = get_Socket();
	System::Net::EndPoint		*Endp = soc->get_RemoteEndPoint();


So when you have this class, you only have to do something like that to get the client's IP address and socket:

NetworkStream * networkStream = pTcpClient->GetStream(); 
MyNetworkStream * myStream =  static_cast<MyNetworkStream *>(networkStream);
ClientIP = myStream->get_IPAddress();
Console::Write(S"Client IP Address ");
networkStream->Read(bytes, 0, (int) pTcpClient->ReceiveBufferSize);

There you go! IP address and everything. Now if you don't use TcpClient, you could AcceptSocket() instead of AcceptTcpClient() to get the socket. When you have the socket you can use get_RemoteEndPoint(), but I thought that you will like to use TcpClient.

Have fun!

Web03 | 2.8.160204.4 | Advertise | Privacy
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service