如何使用Java获取客户端的LAN IP? [英] How to get the LAN IP of a client using Java?

查看:410
本文介绍了如何使用Java获取客户端的LAN IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java获取计算机的LAN IP地址?我想要连接到路由器和网络其余部分的IP地址。

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.

我尝试过这样的事情:

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

这似乎适用于某些情况,但有时会返回loopback-address或完全不同的东西。此外,它需要互联网连接。

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?

编辑:以为这里问题比评论更好..

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

如果你有很多接口怎么办?例如,一个用于电缆,一个用于wifi,一个用于虚拟盒子等。是否无法真正看到哪一个连接到网络?

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?

推荐答案

尝试java.net.NetworkInterface

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

这篇关于如何使用Java获取客户端的LAN IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆