简体   繁体   English

获取客户端静态IP地址

[英]Getting client static IP address

I am deplyong a web application in the Internet and I am checking whether the user's login is valid by checking its client IP address (eg 192.168.2.XXX ). 我正在使用Internet中的Web应用程序,并且正在通过检查其客户端IP地址(例如192.168.2.XXX )来检查用户的登录名是否有效。 Actually, I have found a working code (below). 实际上,我找到了一个有效的代码(如下)。 This code was completely working before, but after some time, its output is not the same anymore. 该代码之前完全可以运行,但是一段时间后,其输出不再相同。 Now, this code only gives me 1 IP address which is the server's IP address. 现在,此代码仅给我1个IP地址,即服务器的IP地址。 What is wrong with my code? 我的代码有什么问题? How can I get the client's static IP address rather than the server's IP address? 如何获得客户端的静态IP地址而不是服务器的IP地址? I have also tried other solutions such as getRemoteAddr() and request.getHeader("PROXY-CLIENT-IP") but it is not working. 我还尝试了其他解决方案,例如getRemoteAddr()request.getHeader("PROXY-CLIENT-IP")但是它不起作用。

Java: Java:

String ipAddress = request.getHeader("X-FORWARDED-FOR");
if(ipAddress == null)
    ipAddress = InetAddress.getLocalHost().getHostAddress();

Your are mixing two levels of abstractions and that is rarely a good thing. 您正在混合两个抽象级别,这很少是一件好事。 The header X-FORWARDED_FOR is inserted by a load balancer or proxy. 标头X-FORWARDED_FOR由负载均衡器或代理插入。 If the client reaches the server directly, then this header isn't present and you are executing this code InetAddress.getLocalHost().getHostAddress(); 如果客户端直接到达服务器,则此标头不存在,并且您正在执行此代码InetAddress.getLocalHost().getHostAddress(); . Which does exactly what you say: It is retrieving the IP address of the host where this piece of code is running, ie the web server. 这正是您所说的:检索正在运行此代码段的主机(即Web服务器)的IP地址。

See also here: Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful? 另请参见此处: 获取客户端IP地址:REMOTE_ADDR,HTTP_X_FORWARDED_FOR,还有什么用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM