如何在Java HttpServletRequest中获取客户端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地址。 请回答。

非常感谢你。

试试这个,

  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/

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

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

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

希望能帮助到你。

  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