我正在使用 JSP、Servlets(容器:Glassfish)开发 Web 应用程序,我需要在其中获取客户端 IP地址.
I am developing a web application using JSP, Servlets (Container: Glassfish) in which I need to get clients IP Address.
我正在获取客户的 IP 地址,因为我只想在办公室内的计算机上授予对某些页面(如客户维护表单)的访问权限,我想限制对办公室外这些页面的访问.
I am getting the clients IP address, because I want to give access to some pages (like Customer maintenance forms) only on computers withing the office, I want to restrict access to those pages outside office.
以下是我目前的代码:
String ipAddress = request.getRemoteAddr(); System.out.println("IP Address: "+ipAddress);路2
String ipAddress=null; String getWay = request.getHeader("VIA"); // Gateway ipAddress = request.getHeader("X-FORWARDED-FOR"); // proxy if(ipAddress==null) { ipAddress = request.getRemoteAddr(); } System.out.println("IP Address: "+ipAddress);每次我重新启动计算机(关机->启动或重新启动)时,上面的代码都会给我不同的 IP 地址.
Above code gives me different IP Address each time when I restart my computer (Shutdown->Start or Restart).
我得到 IP6 喜欢:
fe80:0:0:0:20ca:1776:f5ff:ff15%13让我知道这段代码有什么问题?
Let me know what is wrong with this code?
推荐答案正如@martin 和 这个答案 所解释的那样,它很复杂.没有万无一失的方法来获取客户端的 IP 地址.
As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.
你能做的最好的事情就是尝试解析 "X-Forwarded-For" 并依赖于 request.getRemoteAddr();
The best that you can do is to try to parse "X-Forwarded-For" and rely on request.getRemoteAddr();
public static String getClientIpAddress(HttpServletRequest request) { String xForwardedForHeader = request.getHeader("X-Forwarded-For"); if (xForwardedForHeader == null) { return request.getRemoteAddr(); } else { // As of en.wikipedia/wiki/X-Forwarded-For // The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ... // we only want the client return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim(); } }更多推荐
获取客户端的IP地址
发布评论