Click here to Skip to main content
Click here to Skip to main content

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

, 10 Apr 2002
Rate this:
Please Sign up or sign in to vote.
How to get the clients IP address using TcpClient in Managed C++
<!-- Add the rest of your HTML here -->

Introduction

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);
TcpListener->Start(); 
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:

//MyNetworkStream.h
#pragma once

__gc class MyNetworkStream : public NetworkStream
{
public:
	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()
{
	return(this->get_Socket());
}

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

	return(Endp->ToString());
}

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 ");
Console::WriteLine(ClientIP);
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!

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

Share

About the Author

Albert Pascual
Web Developer
United States United States
Al is just another Software Engineer working in C++, ASp.NET and C#. Enjoys snowboarding in Big Bear, and wait patiently for his daughters to be old enough to write code and snowboard.
 
Al is a Microsoft ASP.NET MVP
 
Blog

Comments and Discussions

 
Generalneed some guide... Pinmemberchal_adiera24-Mar-05 0:10 
hi AL...
 
I am a new beginner in socket programming...vc++.net
Your article very good n give me some guide how to create the class in .net
I want to implement that in my code but the basic stage still got trouble...
I don't no how to fixed it...
 
I have 2 file..server n client..
This code no error and can connected.
But the output not display..
 
Error is << String reference not set to an instance of a String >>
->Byte data[] = Encoding::ASCII->GetBytes(s);
what that mean?
 
can you help me...
see my code..
tq
SERVER file
void main()
{
try
{
Int32 port = 80;
IPAddress* localAddr = IPAddress::Parse(S"127.0.0.1");
 
TcpListener* server = new TcpListener(localAddr, port);
 
server->Start();
 
Byte bytes[] = new Byte[256];
String* data = 0;
 
while (true)
{
Console::Write(S"Waiting for a connection... ");
 
TcpClient* client = server->AcceptTcpClient();
Console::WriteLine(S"Connected!");

data = 0;
 
NetworkStream* stream = client->GetStream();
 
Int32 i;
 
while (i = stream->Read(bytes, 0, bytes->Length))
{
data = Encoding::ASCII->GetString(bytes, 0, i);
Console::WriteLine(String::Format(S"Received: {0}", data));
 
data = data->ToUpper();
 
Byte msg[] = Text::Encoding::ASCII->GetBytes(data);
 
stream->Write(msg, 0, msg->Length);
Console::WriteLine(String::Format(S"Sent: {0}", data));
}
client->Close();
}
}

catch (SocketException* e)
{
Console::WriteLine(S"SocketException: {0}", e);
}
 
Console::WriteLine(S"\nHit enter to continue...");
Console::Read();
}
CLIENT file:
 
String* Connect(String* server, String* message)
{
try {

Int32 port = 80;
TcpClient* client = new TcpClient(server,port);

Byte data[] = Encoding::ASCII->GetBytes(message);
 
NetworkStream* stream = client->GetStream();
 
stream->Write(data, 0, data->Length);

Console::WriteLine(S"Sent: {0}", message);

String* responseData = String::Empty;
 
Int32 bytes = stream->Read(data, 0, data->Length);
responseData =Encoding::ASCII->GetString(data, 0, bytes);
Console::WriteLine(S"Received: {0}", responseData);
 
client->Close();
 
} catch (ArgumentNullException* e) {
Console::WriteLine(S"ArgumentNullException: {0}", e);
} catch (SocketException* e) {
Console::WriteLine(S"SocketException: {0}", e);
}
 
Console::WriteLine(S"\n Press Enter to continue...");
Console::Read();
}
 

int main()
{

String* message;
String* server;

String* result = Connect(server,message);
Console::WriteLine(result);
}
 

 
salwa(beginner)

GeneralRe: need some guide... Pinmembermmatchyn18-Nov-05 14:54 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 11 Apr 2002
Article Copyright 2002 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid