servlets—如何在JavaHttpServletRequest中获取客户端ip地址

f1tvaqid  于 2021-07-09  发布在  Java
关注(0)|答案(4)|浏览(352)

我正在尝试开发一个javaweb应用程序(servlet),我需要它来获取客户机的ip地址。
以下是我目前的代码:

String ipAddress =  request.getRemoteAddr();

在这种情况下,大部分时间我都会得到“默认网关地址”(147.120.1.5)。不是我的机器ip地址(174.120.100.17)。

String ipAddress = request.getHeader("X-FORWARDED-FOR");  
if (ipAddress == null) {  
    ipAddress = request.getRemoteAddr();  
}

在这种情况下,大部分时间我都会得到“默认网关地址”(147.120.1.5)。不是我的机器ip地址(174.120.100.17)。

InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.getHostAddress());

在本例中,我得到了服务器ip地址(147.120.20.1)。
我的ip地址是147.120.100.17。现在我不知道如何获得真正的客户端ip地址。
非常感谢你。

wlwcrazw

wlwcrazw1#

试试这个,

String ipAddress = request.getHeader("X-FORWARDED-FOR");  
if (ipAddress == null) {  
    ipAddress = request.getRemoteAddr();  
}

参考文献:http://www.mkyong.com/java/how-to-get-client-ip-address-in-java/

jhdbpxl9

jhdbpxl92#

试试这个。在任何情况下

private static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR" };

private String getClientIpAddress(HttpServletRequest request) {
    for (String header : HEADERS_TO_TRY) {
        String ip = request.getHeader(header);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
    }

    return request.getRemoteAddr();
}
pbossiut

pbossiut3#

如果您试图获取dev环境的ip地址,那么您可以使用this:-

public String processRegistrationForm(HttpServletRequest request)
{
    String appUrl = request.getScheme() + "://"+ request.getLocalAddr();
    return appUrl;
}

这个 request.getLocalAddr() 将返回请求接收系统的ip地址。
希望有帮助。

qzwqbdag

qzwqbdag4#

import java.net.UnknownHostException;

/**
 * Simple Java program to find IP Address of localhost. This program uses
 * InetAddress from java.net package to find IP address.
 *
 */
public class IPTest { 

public static void main(String args[]) throws UnknownHostException {

    InetAddress addr = InetAddress.getLocalHost();

    //Getting IPAddress of localhost - getHostAddress return IP Address
    // in textual format
    String ipAddress = addr.getHostAddress();

    System.out.println("IP address of localhost from Java Program: " + ipAddress);

    //Hostname
    String hostname = addr.getHostName();
    System.out.println("Name of hostname : " + hostname);     
}
}

输出:

IP address of localhost from Java Program: 190.12.209.123
Name of hostname : PCLOND3433

相关问题