Can you determine the source IP and port from a connected TCP socket?

醉酒当歌 提交于 2019-12-25 06:21:01

问题


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.


回答1:


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));



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6296258/can-you-determine-the-source-ip-and-port-from-a-connected-tcp-socket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!