How to get client ip address in Java HttpServletRequest

I am trying to develop a Java web application (Servlet) that I need to get clients IP address.

Please do not consider this a duplicate question, because I have tried all possible answers that are available in stackoverflow.

Below is my code:

one)

String ipAddress = request.getRemoteAddr(); 

In this case, most of the volume I get is the "Default Gateway Address" (147.120.1.5). not my device IP address (174.120.100.17).

2)

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

In this case, most of the volume I get is the "Default Gateway Address" (147.120.1.5). not my device IP address (174.120.100.17).

3)

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

In this case, I got the IP address of the server (147.120.20.1).

My IP address is at 147.120.100.17. No, I don’t know how to get the real IP address of the client. Please make an answer.

Many thanks.

+16
java servlets ip
source share
4 answers

Try it,

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

link: http://www.mkyong.com/java/how-to-get-client-ip-address-in-java/

+42
source

In case you are trying to get the IP address for the Dev environment, you can use this: -

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

request.getLocalAddr() will return the IP address of the request receiving system.

Hope it helps.

0
source

Try this. for all conditions

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

Output:

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

All Articles