如何使用Java获取LAN IP地址

时间:2015-05-24 02:00:42

标签: java server inetaddress

我想获取我的局域网IP地址。但我使用此代码显示Localhost地址。

public static void main(String[] args)
{
try
{
    InetAddress add=InetAddress.getLocalHost();
    System.out.println("Local IP: " + add.getHostAddress());
}
catch(Exception ex)
{
    System.out.println(ex.getMessage());
}        
}

它显示IP是:127.0.1.1。 但我的局域网IP地址是10.107.46.88

1 个答案:

答案 0 :(得分:1)

我知道最简单的方法是使用NetworkInterface.getNetworkInterfaces(),并且链接的Javadoc指出您可以使用getNetworkInterfaces() + getInetAddresses()来获取此节点的所有IP地址。这可能看起来像

try {
    Enumeration<NetworkInterface> nics = NetworkInterface
            .getNetworkInterfaces();
    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        Enumeration<InetAddress> addrs = nic.getInetAddresses();
        while (addrs.hasMoreElements()) {
            InetAddress addr = addrs.nextElement();
            System.out.printf("%s %s%n", nic.getName(),
                    addr.getHostAddress());
        }
    }
} catch (SocketException e) {
    e.printStackTrace();
}

我得到了(对于我的网络)

wlan0 192.168.2.9
lo 127.0.0.1

如果您不想显示环回,则可以使用isLoopback()测试NetworkInterface

while (nics.hasMoreElements()) {
    NetworkInterface nic = nics.nextElement();
    if (!nic.isLoopback()) {
        // ... as before
    }
}