Sunday, September 2, 2012

Obtaining a List of IP Addresses

During our final year project I wanted to get active ip addresses of a node. This is easily doable using
The method below returns a list of IP addresses of a machine except those belonging to loopback or inactive network interfaces. The addresses can be further classified as IPv4 or IPv6 using instance check with and
    public static List<InetAddress> getIPAddress() throws SocketException {

        List<InetAddress> ipAddresses = new ArrayList<InetAddress>();
        Enumeration e;
        e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) e.nextElement();
            if (ni.isLoopback() || !ni.isUp()) continue;

            for (Enumeration e2 = ni.getInetAddresses(); e2.hasMoreElements(); ) {
                InetAddress ip = (InetAddress) e2.nextElement();
        return ipAddresses;

No comments: