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

前端 未结 5 978
攒了一身酷
攒了一身酷 2021-02-06 09:22

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

5条回答
  •  天涯浪人
    2021-02-06 09:36

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

提交回复
热议问题