0

I am using the following code to get the IP address form a client.

public String getIp(@Context HttpServletRequest requestContext, @Context SecurityContext context) {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    return ipAddress;
}

However, when it executes, it returns 0:0:0:0:0:0:0:1. It is running on my local pc, and I would expect it to return good ol 127.0.0.1. Any ideas why not?

user489041
  • 27,916
  • 55
  • 135
  • 204
  • possible duplicate of [Getting IP address of client](http://stackoverflow.com/questions/16558869/getting-ip-address-of-client) – Mitesh Pathak Dec 19 '13 at 16:50
  • Not a duplicate. The question is not about getting the IP address, but about why it is 0:0:0:0:0:0:0:1 instead of 127.0.0.1 – Javier Dec 19 '13 at 17:20
  • 1
    `0:0:0:0:0:0:0:1` is an IPv6 IP address. You need to ensure you set it to IPv4 if you want only the IPv4 response. See @Javier's answer. – brandonscript Dec 19 '13 at 18:01

3 Answers3

1

However, when it executes, it returns 0:0:0:0:0:0:0:1. It is running on my local pc, and I >would expect it to return good ol 127.0.0.1. Any ideas why not?

If the machine is behind a proxy you won't be able to get it's local IP or domain information, in any server side technology

Refer [1] Getting IP address of client

Community
  • 1
  • 1
Mitesh Pathak
  • 1,306
  • 10
  • 14
1

Your machine has dual stack (IPv4/IPv6). The 0:0:0:0:0:0:0:1 address (also written as ::1) is the IPv6 equivalent for localhost.

Javier
  • 12,100
  • 5
  • 46
  • 57
1

This is late but for those who will visit this page in the future. If you are running Tomcat, you may set JAVA_OPTS environment variable and add

-Djava.net.preferIPv4Stack=true 

and

-Djava.net.preferIPv4Addresses=true

In eclipse it maybe added in:

Debug As -> Debug configuration -> Environment.

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71