Java Getting IPv4 Address

淺唱寂寞╮ 提交于 2019-12-04 07:42:27

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