Java Getting IPv4 Address

雨燕双飞 提交于 2019-12-06 02:19:36

问题


Regarding this link where using the codes provided to produce the IP addresses.

String ip;
    try {
       Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp())
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                ip = addr.getHostAddress();
                System.out.println(iface.getDisplayName() + " " + ip);
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }

I have implement the exact codes to get the IP addresses but it provides both the IPv4 and IPv6 addresses. Below is the value that was produced.

Qualcomm Atheros AR5BWB222 Wireless Network Adapter 192.168.1.5
Qualcomm Atheros AR5BWB222 Wireless Network Adapter fe80:0:0:0:a874:xxxx:xxxx:9150%wlan0

(IPv6 address redacted)

Is there any way that I could only get the IPv4 value and not both?


回答1:


You can check the type of the addr object to see if it's an Inet4Address or an Inet6Address instance.

For example:

String ip;
try {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        // filters out 127.0.0.1 and inactive interfaces
        if (iface.isLoopback() || !iface.isUp())
            continue;

        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while(addresses.hasMoreElements()) {
            InetAddress addr = addresses.nextElement();

            // *EDIT*
            if (addr instanceof Inet6Address) continue;

            ip = addr.getHostAddress();
            System.out.println(iface.getDisplayName() + " " + ip);
        }
    }
} catch (SocketException e) {
    throw new RuntimeException(e);
}


来源:https://stackoverflow.com/questions/40912417/java-getting-ipv4-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!