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?

3
  • possible duplicate of Getting IP address of client Commented Dec 19, 2013 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 Commented Dec 19, 2013 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. Commented Dec 19, 2013 at 18:01

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Best to provide the details how to set it to capture only IPv4 info ;)
The server should be bound to an IPv4 address, otherwise it listen on every address, and IPv6 is given preference.
Right, but you can choose to bind only to the ipv4 interface.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.