Java Getting IPv4 Address

Fouzy picture Fouzy · Dec 1, 2016 · Viewed 10.7k times · Source

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?

Answer

Alastair McCormack picture Alastair McCormack · Dec 1, 2016

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