简体   繁体   English

Java获取IPv4地址

[英]Java Getting IPv4 Address

Regarding this link where using the codes provided to produce the IP addresses. 对于这个链接了使用设置来产生IP地址的代码。

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. 我已经实现了确切的代码来获取IP地址,但它提供了IPv4和IPv6地址。 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) (IPv6地址编辑)

Is there any way that I could only get the IPv4 value and not both? 有什么方法我只能获得IPv4值,而不是两者兼而有之?

You can check the type of the addr object to see if it's an Inet4Address or an Inet6Address instance. 您可以检查addr对象的类型,以查看它是Inet4Address还是Inet6Address实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM