如何使用的TcpClient我收到客户端的IP地址?如何使用、客户端、地址、TcpClient

2023-09-03 12:06:26 作者:军刀

我使用的TcpClient到端口的请求上进行监听。当请求从客户端进来,我想知道客户端IP发出请求。

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.

我已经试过:

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

所有这些都是私有地址,显然不是的把我的网络客户端发出请求的地址,这些地址输出10.xxx地址。我能做些什么来获得发出请求的客户端的公网IP​​?

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?

编辑: 我们使用的是亚马逊的EC2负载平衡器使用TCP转发。有没有一种方法来获得真正的客户机IP在这一套了?

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?

推荐答案

这听起来也许你的服务器是在负载平衡器或路由器使用的 NAT 的。在这种情况下,该IP包将不会有始发客户端的地址,但在NAT路由器的地址。只有NAT路由器知道发件人的地址(在IP级)。

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

根据您可能会使用在TCP之上的任何高层协议,你可以得到来自客户身份,但它更容易在较高的水平恶搞这样的信息,如果这可能是一个问题。

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.

如果你需要这个数据只用于研究目的,你的NAT设备可以保留日志。

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

如果是,你得到实时的真实原始IP数据包的要求,你可能要重新配置你的路由器或者服务器移动到DMZ,但是这是蜡的整体诺特尔球。向您的网络人员,因为他们肯定会知道更多关于这方面比我(我不是一个网络专家)。

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