Can I filter and select only IPV4 adresses on the InetAddress object? How to exlude the IPV6?

6.6k views Asked by At

I have the following problem: I create an ArrayList and I put in this arraylist all the IP addresses of my client (one if the client have a single network card, n if the client run on a PC having n network card) excluding the loopback adress, the point to point adress and the virtual adress.

I have do this in this way:

private static List<String> allIps = new ArrayList<String>();

static {
    Enumeration<NetworkInterface> nets;
    try {

        nets = NetworkInterface.getNetworkInterfaces();


        while(nets.hasMoreElements()) {

            NetworkInterface current = nets.nextElement();

            if ((current.isUp()) && (!current.isPointToPoint()) && (!current.isVirtual()) && (!current.isLoopback())) {
                System.out.println(current.getName());
                Enumeration<InetAddress> ee = current.getInetAddresses();


                    while (ee.hasMoreElements()) {
                        InetAddress i = ee.nextElement();
                        System.out.println(i.getHostAddress());
                        allIps.add(i.getHostAddress());

                    }
            }
        }
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println("List of all IP on this client: "
            + allIps.toString());
    System.out.println("Number of ip: " + allIps.size());

}

It seems work well, the only problem is that my output (in the Eclipse console) is:

eth0
fe80:0:0:0:20c:29ff:fe15:3dfe%2
192.168.15.135
List of all IP on this client: [fe80:0:0:0:20c:29ff:fe15:3dfe%2, 192.168.15.135]
Number of ip: 2

Using the debugger and the console output appear clear to me that, in this case, the only network interface present is eth0 (and this is ok) but, for this network interface, id found 2 IP adresses (the fits one is IPV6 address, the second one is the classic IPV4 address)

So it put in my adresses list allIps both.

I want select and put in my allIps list only the IPV4 adresses and not also the IPV6. What can I do to do it? Can I filter and select only IPV4 on my InetAddress object?

Tnx

Andrea

1

There are 1 answers

0
McDowell On

Use instanceof and the Inet4Address type:

for (NetworkInterface ni :
                     Collections.list(NetworkInterface.getNetworkInterfaces())) {
  for (InetAddress address : Collections.list(ni.getInetAddresses())) {
    if (address instanceof Inet4Address) {
      System.out.println(address);
    }
  }
}