如何在Java HttpServletRequest

时间:2015-04-28 04:00:38

标签: java servlets ip

我正在尝试开发一个Java Web应用程序(Servlet),我需要获取客户端的IP地址。

请不要将此视为重复问题,因为我尝试了stackoverflow中可用的所有可能答案。

以下是我的代码:

1)

String ipAddress =  request.getRemoteAddr();

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

2)

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

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

3)

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

在这种情况下,我得到了服务器IP地址(147.120.20.1)。

我在147.120.100.17中的IP地址。现在我不知道如何获取真正的客户端IP地址。请回答。

非常感谢。

4 个答案:

答案 0 :(得分:40)

试试这个,

    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/

答案 1 :(得分:0)

如果您正在尝试获取Dev-environment的IP地址,那么您可以使用: -

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

request.getLocalAddr()将返回请求接收系统的IP地址。

希望它有所帮助。

答案 2 :(得分:0)

尝试这个。在所有情况下

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

答案 3 :(得分:-1)

 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