java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?

I'm writing a simple networking app. I need to know the real IP of my machine on the network, like 192.168.1.3 . getLocalHost returns 127.0.0.1 (on Linux, I don't know if it is the same on windows). How to do it?


If you actually want to work with all of the IP addresses on the machine you can get those with the NetworkInterface class. Of course, then you need to which one you actually want to use, but that's going to be different depending on what you're using it for, or you might need to expand the way you're using it to account for multiple addresses.

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

public class ShowInterfaces
{
        public static void main(String[] args) throws Exception
        {
                System.out.println("Host addr: " + InetAddress.getLocalHost().getHostAddress());  // often returns "127.0.0.1"
                Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
                for (; n.hasMoreElements();)
                {
                        NetworkInterface e = n.nextElement();
                        System.out.println("Interface: " + e.getName());
                        Enumeration<InetAddress> a = e.getInetAddresses();
                        for (; a.hasMoreElements();)
                        {
                                InetAddress addr = a.nextElement();
                                System.out.println("  " + addr.getHostAddress());
                        }
                }
        }
}

As the machine might have multiple addresses, it's hard to determine which one is the one for you. Normally, you want the system to assign an IP based on its routing table. As the result depends on the IP you'd like to connect to, there is a simple trick: Simply create a connection and see what address you've got from the OS:

// output on my machine: "192.168.1.102"
Socket s = new Socket("192.168.1.1", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();

// output on my machine: "127.0.1.1"
System.out.println(InetAddress.getLocalHost().getHostAddress());

I'm not sure whether it's possible to do this without establishing a connection though. I think I've once managed to do it with Perl (or C?), but don't ask me about Java. I think it might be possible to create a UDP socket (DatagramSocket) without actually connecting it.

If there is a NAT router on the way you won't be able to get the IP that remote hosts will see though. However, as you gave 192.* as an example, I think you don't care.


To fix it:

  1. Find your host name. Type: hostname. For example, you find your hostname is mycomputer.xzy.com

  2. Put your host name in your hosts file. /etc/hosts . Such as

    10.50.16.136 mycomputer.xzy.com