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:
String ipAddress = request.getRemoteAddr(); System.out.println("IP Address: "+ipAddress);
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?
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.
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.
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.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With