Java IP Address Get getAllLocalIPs()

Here you can find the source of getAllLocalIPs()

Description

Returns all available IP addresses.

License

Open Source License

Return

Returns all IP addresses (can be an empty list in error case or if network connection is missing).

Declaration

public static Collection<InetAddress> getAllLocalIPs() 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedList;

public class Main {
    /**//  ww  w  .  j  a va2s  .c  o m
     * Returns all available IP addresses.
     * <p>
     * To get the first/main local ip only you could use also
     * {@link #getLocalIP() }.
     * <p>
     * In error case or if no network connection is established, we return
     * an empty list here.
     * <p>
     * Loopback addresses are excluded - so 127.0.0.1 will not be never
     * returned.
     * <p>
     * The "primary" IP might not be the first one in the returned list.
     *
     * @return  Returns all IP addresses (can be an empty list in error case
     *          or if network connection is missing).
     * @since   0.1.0
     * 
     * http://it-tactics.blogspot.com/2010/07/get-reliable-local-ip-address-in-java.html
     * 7.12.2011
        
     * 
     */
    public static Collection<InetAddress> getAllLocalIPs() {
        final LinkedList<InetAddress> listAdr = new LinkedList<InetAddress>();
        try {
            final Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
            if (nifs == null) {
                return listAdr;
            }

            while (nifs.hasMoreElements()) {
                final NetworkInterface nif = nifs.nextElement();
                // We ignore subinterfaces - as not yet needed.

                final Enumeration<InetAddress> adrs = nif.getInetAddresses();
                while (adrs.hasMoreElements()) {
                    final InetAddress adr = adrs.nextElement();
                    if (adr != null && !adr.isLoopbackAddress()
                            && (nif.isPointToPoint() || !adr.isLinkLocalAddress())) {
                        listAdr.add(adr);
                    }
                }
            }
            return listAdr;
        } catch (final SocketException ex) {
            //            Logger.getLogger(Net.class.getName()).log(Level.WARNING, "No IP address available", ex);
            return listAdr;
        }
    }
}

Related

  1. getAllIPAddresses()
  2. getAllIPsAndAssignedBroadcastAddresses()
  3. getALLLocalHostIP()
  4. getAllLocalIP()
  5. getAllLocalIP()
  6. getAllLocalIpv4Addresses()
  7. getAllMyHostIPV4Adresses()
  8. getAllUsableIPAddresses()
  9. getExternalIP()