获取客户端的 IP 地址

2022-08-31 20:06:57

我正在使用JSPServlets(容器:Glassfish)开发一个Web应用程序,我需要在其中获取客户端。IP Address

我正在获取客户端 IP 地址,因为我想仅在具有办公室的计算机上授予对某些页面(如客户维护表单)的访问权限,因此我想限制对办公室外这些页面的访问。

以下是我到目前为止的代码:

方式1

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

上面的代码每次重新启动计算机时都会给我(关机>启动或重新启动)。different IP Address

我变得像:IP6

fe80:0:0:0:20ca:1776:f5ff:ff15%13

让我知道此代码有什么问题?


答案 1

正如@martin和这个答案所解释的那样,它很复杂。没有防弹方法来获取客户端的IP地址。

你能做的最好的事情就是尝试解析和依赖"X-Forwarded-For"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();
    }
}

答案 2

我使用以下静态帮助程序方法来检索客户端的 IP:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_VIA");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("REMOTE_ADDR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getRemoteAddr();  
    }  
    return ip;  
}

推荐