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

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());
                        }
                }
        }
}

Leave a Comment