How to get the LAN IP of a client using Java?

cragiz picture cragiz · May 16, 2010 · Viewed 18.2k times · Source

How can i get the LAN IP-address of a computer using Java? I want the IP-address which is connected to the router and the rest of the network.

I've tried something like this:

Socket s = new Socket("www.google.com", 80);
String ip = s.getLocalAddress().getHostAddress();
s.close();

This seem to work on some cases, but sometimes it returns the loopback-address or something completely different. Also, it requires internet connection.

Does anyone got a more accurate method of doing this?

EDIT: Thought it would be better to ask here than in a comment..

What if you got many interfaces? For example, one for cable, one for wifi and one for virtual box or so. Is it impossible to actually see which one is connected to the network?

Answer

Alexander Pogrebnyak picture Alexander Pogrebnyak · May 16, 2010

Try java.net.NetworkInterface

import java.net.NetworkInterface;

...

for (
    final Enumeration< NetworkInterface > interfaces =
        NetworkInterface.getNetworkInterfaces( );
    interfaces.hasMoreElements( );
)
{
    final NetworkInterface cur = interfaces.nextElement( );

    if ( cur.isLoopback( ) )
    {
        continue;
    }

    System.out.println( "interface " + cur.getName( ) );

    for ( final InterfaceAddress addr : cur.getInterfaceAddresses( ) )
    {
        final InetAddress inet_addr = addr.getAddress( );

        if ( !( inet_addr instanceof Inet4Address ) )
        {
            continue;
        }

        System.out.println(
            "  address: " + inet_addr.getHostAddress( ) +
            "/" + addr.getNetworkPrefixLength( )
        );

        System.out.println(
            "  broadcast address: " +
                addr.getBroadcast( ).getHostAddress( )
        );
    }
}