Java获取IPv4地址 [英] Java Getting IPv4 Address

查看:698
本文介绍了Java获取IPv4地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于链接,其中使用提供的代码生成IP地址。

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

我已经实现了确切的代码来获取IP地址,但它同时提供了IPv4和IPv6地址。以下是生成的值。

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地址编辑)

有什么办法我只能得到IPv4值,而不是两者都有?

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

推荐答案

您可以检查 addr 对象的类型,看它是 Inet4Address 还是 Inet6Address instance。

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

例如:

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

这篇关于Java获取IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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