Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting IP address of client [duplicate]

I am developing a web application using JSP, Servlets (Container: Glassfish) in which I need to get clients IP Address.

I am getting the clients IP address, because I want to give access to some pages (like Customer maintenance forms) only on computers withing the office, I want to restrict access to those pages outside office.

Following is my code so far:

way1

String ipAddress =  request.getRemoteAddr(); System.out.println("IP Address: "+ipAddress); 

way2

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

Above code gives me different IP Address each time when I restart my computer (Shutdown->Start or Restart).

I am getting IP6 like:

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

Let me know what is wrong with this code?

like image 393
Bhushan Avatar asked May 15 '13 07:05

Bhushan


People also ask

How do I trace duplicate IP addresses?

Here is how you can check it: On an unaffected host on the same network, open up a command prompt. On a Windows machine, type "arp -a [suspected duplicate IP]" and hit enter. On a Mac or Linux machine, type "arp [suspected duplicate IP]" and hit enter.

Can IP address be duplicate?

If you mistakenly assign the same static address to two devices, you'll run into a duplicate IP error. This problem can also arise if you set a device to use a static IP without reserving that address in your router. Eventually, your router will try to hand out that address to another device, creating an IP conflict.

Why is there a duplicate address detected for the IP address?

NOTE: A Duplicate IP Address error message occurs when another device, such as a Laptop, Desktop, Cell Phone or Tablet has connected to the Network, and obtained the same IP Address from the DHCP Server that is in use by the Printer.


1 Answers

As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.

The best that you can do is to try to parse "X-Forwarded-For" and rely on 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();     } } 
like image 192
Xavier Delamotte Avatar answered Sep 21 '22 16:09

Xavier Delamotte