brendan
brendan

Reputation: 29986

How do I get a client's IP address from behind a load balancer?

I am using TcpClient to listen on a port for requests. When the requests come in from the client I want to know the client ip making the request.

I've tried:

Console.WriteLine(tcpClient.Client.RemoteEndPoint.ToString());
Console.WriteLine(tcpClient.Client.LocalEndPoint.ToString());
var networkStream = tcpClient.GetStream();
var pi = networkStream.GetType().GetProperty("Socket", BindingFlags.NonPublic | BindingFlags.Instance);
var socketIp = ((Socket)pi.GetValue(networkStream, null)).RemoteEndPoint.ToString();
Console.WriteLine(socketIp);

All of these addresses output 10.x.x.x addresses which are private addresses and are clearly not the address of the clients off my network making the requests. What can I do to get the public ip of the clients making the requests?

Edit: We are using an Amazon EC2 Load Balancer with tcp forwarding. Is there a way to get the true client ip in this set up?

Upvotes: 43

Views: 87184

Answers (4)

Haroon Rasheed
Haroon Rasheed

Reputation: 21

Simply use the connection socket object of Socket class which you have used to accept the client.

connectionSocket.RemoteEndPoint.toString();

Upvotes: 2

Avgardisme
Avgardisme

Reputation: 21

AdresseIP = DirectCast(SocketClient.Client.RemoteEndPoint, IPEndPoint).Address.ToString

Upvotes: -5

Kelsey
Kelsey

Reputation: 47736

Does this work:

((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()

If the client is connecting to you via an internal network I am not sure you can get their public IP since the connection to get back to the client would not need that information.

Upvotes: 106

P Daddy
P Daddy

Reputation: 29537

It sounds like perhaps your server is behind a load balancer or router using NAT. In this case, the IP packet won't have the originating client's address, but the address of the NAT router. Only the NAT router knows the sender's address (on an IP level).

Depending on whatever higher-level protocol you might be using on top of TCP, you may be able to get client identification from that, although it's much easier to spoof such information at higher levels, if that may be a concern.

If you need this data only for research purposes, your NAT device may keep a log.

If it's a requirement that you get the true originating IP packet in real time, you may have to have to reconfigure your router or have your server moved to the DMZ, but that's a whole nother ball of wax. Talk to your network guys, as they would certainly know more about this than I (I'm not a network expert).

Upvotes: 6

Related Questions