我正在使用 TcpClient 在端口上监听请求。当请求来自客户端时,我想知道发出请求的客户端 ip。
我试过:
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.x.x.x 地址,这些地址是私有(private)地址,显然不是发出请求的我网络外的客户端的地址。我该怎么做才能获得发出请求的客户端的公共(public) IP?
编辑: 我们正在使用具有 tcp 转发功能的 Amazon EC2 负载均衡器。有没有办法在此设置中获取真实的客户端 ip?
最佳答案
这行吗:
((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()
如果客户端通过内部网络连接到您,我不确定您是否可以获得他们的公共(public) IP,因为返回客户端的连接不需要该信息。
关于c# - 如何从负载均衡器后面获取客户端的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2717381/