0

I'd like to have my server determine the source IP and port of a client from a connected TCP socket. Since my clients are likely behind NAT's, I can't rely on being told by the client (in the protocol of the connection)... If this is possible, I'm going to need to implement it on both Windows and Linux... But an answer for either would help get me started...

I am using C, and I'm looking for either libc or msvcrt based solutions.

Rafael Colucci
  • 6,018
  • 4
  • 52
  • 121
dicroce
  • 45,396
  • 28
  • 101
  • 140

3 Answers3

3

In case the peer is behind NAT, you can be talking about two different IPs (it's unclear from your question which one you want):

  • the IP of the peer in the internal network (e.g. 192.168.1.2);
  • the external IP of the NAT itself

In the former case, there is no solution available from the TCP/IP stack: this information just doesn't exist there on your host, since the NAT replaces all internal IPs with its own IP for every packet. So the only solution would be for you to support this functionality in your protocol.

In the latter case, you can just ask the TCP/IP stack: getpeername() is how you do it.

Rom
  • 4,129
  • 23
  • 18
3

Should work both in linux and windows:

struct sockaddr_in addr;
socklen_t len;

len = sizeof addr;
getpeername(clientSocket, (struct sockaddr*)&addr, &len);
printf("Remote IP address: %s\n", inet_ntoa(addr.sin_addr));
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • where did he say that he wanted a ipv6 solution? – jgauffin Jun 10 '11 at 06:37
  • Where did he say that he didn't? It's just something to be aware of - I voted this answer *up* (unqualified "IP" says IPv4 or IPv6 to me). – caf Jun 10 '11 at 07:26
0

If your clients are behind a NAT, there's not way of detecting the remote IP. If you try to do so, you will get the NAT ip always. The only way I know is sending the client IP together with the request to your server (as part of the request).

But you are not clear about what you want. You are not telling us what language you are using, neither what kind of server you are talking about. This will prevent us to give you a helpful answer.

Rafael Colucci
  • 6,018
  • 4
  • 52
  • 121