0

I want to get my LAN IP address. But I it shows Localhost address using this code.

public static void main(String[] args)
{
try
{
    InetAddress add=InetAddress.getLocalHost();
    System.out.println("Local IP: " + add.getHostAddress());
}
catch(Exception ex)
{
    System.out.println(ex.getMessage());
}        
}

It shows IP is : 127.0.1.1 . But my LAN ip address is 10.107.46.88

Uzzal
  • 21
  • 4
  • Please [edit] your question to explain what the result of the code listed actually is and why that's not useful. Thanks for improving the question's reference value and making it more answerable! – Nathan Tuggy May 24 '15 at 02:05
  • you want to retrieve your public ip address, not the local ip – vandale May 24 '15 at 02:18

1 Answers1

3

The easiest way I know is to use NetworkInterface.getNetworkInterfaces() and the linked Javadoc notes that you can use getNetworkInterfaces()+getInetAddresses() to obtain all IP addresses for this node. That might look something like

try {
    Enumeration<NetworkInterface> nics = NetworkInterface
            .getNetworkInterfaces();
    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        Enumeration<InetAddress> addrs = nic.getInetAddresses();
        while (addrs.hasMoreElements()) {
            InetAddress addr = addrs.nextElement();
            System.out.printf("%s %s%n", nic.getName(),
                    addr.getHostAddress());
        }
    }
} catch (SocketException e) {
    e.printStackTrace();
}

and I get (for my network)

wlan0 192.168.2.9
lo 127.0.0.1

if you don't want to display loop-back you can test the NetworkInterface with isLoopback().

while (nics.hasMoreElements()) {
    NetworkInterface nic = nics.nextElement();
    if (!nic.isLoopback()) {
        // ... as before
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249