10

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?

Community
  • 1
  • 1
Fouzy
  • 127
  • 1
  • 1
  • 6

1 Answers1

16

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);
}
Alastair McCormack
  • 23,069
  • 7
  • 60
  • 87