获取计算机的LAN IP地址?我想要连接到路由器和网络其余部分的IP地址.
我尝试过这样的事情:
Socket s = new Socket("www.google.com", 80); String ip = s.getLocalAddress().getHostAddress(); s.close();
这似乎适用于某些情况,但有时它会返回loopback-address或完全不同的东西.此外,它需要互联网连接.
有没有人有更准确的方法这样做?
编辑:认为这里问题比评论更好..
如果你有很多接口怎么办?例如,一个用于电缆,一个用于wifi,一个用于虚拟盒子等.实际上看不到哪个连接到网络是不可能的?
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( ) ); } }
翻译自:https://stackoverflow.com/questions/2845279/how-to-get-the-lan-ip-of-a-client-using-java