获取客户端的IP地址 [英] Getting IP address of client

查看:52
本文介绍了获取客户端的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSPServlets(容器: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 https://en.wikipedia.org/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地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆