Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP Address not obtained in java

Tags:

This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there something that I need to watch at linux OS.

import java.util.*;
import java.lang.*;
import java.net.*;

public class GetOwnIP
{
  public static void main(String args[]) {
    try{
      InetAddress ownIP=InetAddress.getLocalHost();
      System.out.println("IP of my system is := "+ownIP.getHostAddress());
    }catch (Exception e){
      System.out.println("Exception caught ="+e.getMessage());
    }
  }
}
like image 674
nilesh Avatar asked Jun 30 '09 06:06

nilesh


People also ask

How do I get my IP in Java?

In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress. getHostName() to get Hostname of the current Server name.

How do you check IP address is valid or not in Java?

We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.

How is an IP address represented in Java?

An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. There are 2 types of addresses : Unicast — An identifier for a single interface.

What is the format of IP address in Java?

The IP address is a string in the form “A.B.C.D”, where the value of A, B, C, and D may range from 0 to 255.


2 Answers

127.0.0.1 is the loopback adapter - it's a perfectly correct response to the (somewhat malfomed) question "what is my IP address?"

The problem is that there are multiple correct answers to that question.

EDIT: The docs for getLocalHost say:

If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned.

Is it possible that the change in behaviour is due to a change in permissions?

EDIT: I believe that NetworkInterface.getNetworkInterfaces is what you need to enumerate all the possibilities. Here's an example which doesn't show virtual addresses, but works for "main" interfaces:

import java.net.*;
import java.util.*;

public class Test
{
    public static void main(String[] args)
        throws Exception // Just for simplicity
    {
        for (Enumeration<NetworkInterface> ifaces = 
               NetworkInterface.getNetworkInterfaces();
             ifaces.hasMoreElements(); )
        {
            NetworkInterface iface = ifaces.nextElement();
            System.out.println(iface.getName() + ":");
            for (Enumeration<InetAddress> addresses =
                   iface.getInetAddresses();
                 addresses.hasMoreElements(); )
            {
                InetAddress address = addresses.nextElement();
                System.out.println("  " + address);
            }
        }
    }
}

(I'd forgotten just how awful the Enumeration<T> type is to work with directly!)

Here are the results on my laptop right now:

lo:
  /127.0.0.1
eth0:
  /169.254.148.66
eth1:
eth2:
ppp0:
  /10.54.251.111

(I don't think that's giving away any hugely sensitive information :)

If you know which network interface you want to use, call NetworkInterface.getByName(...) and then look at the addresses for that interface (as shown in the code above).

like image 133
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet


When you use InetAddress.getLocalHost() you are not guaranteed to get a particular interface, ie. you could receive the loopback (127) interface or a connected one.

In order to ensure you always get an external interface, you should use the java.net.NetworkInterface class. The static getByName(String) class will give you the interface with the defined name (such as "eth0"). Then you can use the getInetAddresses() function to obtain the IP addresses (could be just one) bound to that interface.

NetworkInterface ni = NetworkInterface.getByName("eth1");
ni.getInetAddresses();
like image 41
omerkudat Avatar answered Sep 22 '22 14:09

omerkudat