Advertisement
Guest User

Untitled

a guest
Jul 15th, 2010
2,181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1.     /**
  2.      * Returns all available IP addresses.
  3.      * <p>
  4.      * To get the first/main local ip only you could use also
  5.      * {@link #getLocalIP() }.
  6.      * <p>
  7.      * In error case or if no network connection is established, we return
  8.      * an empty list here.
  9.      * <p>
  10.      * Loopback addresses are excluded - so 127.0.0.1 will not be never
  11.      * returned.
  12.      * <p>
  13.      * The "primary" IP might not be the first one in the returned list.
  14.      *
  15.      * @return  Returns all IP addresses (can be an empty list in error case
  16.      *          or if network connection is missing).
  17.      * @since   0.1.0
  18.      */
  19.     public static Collection<InetAddress> getAllLocalIPs()
  20.     {
  21.         LinkedList<InetAddress> listAdr = new LinkedList<InetAddress>();
  22.         try
  23.         {
  24.             Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
  25.             if (nifs == null) return listAdr;
  26.  
  27.             while (nifs.hasMoreElements())
  28.             {
  29.                 NetworkInterface nif = nifs.nextElement();
  30.                 // We ignore subinterfaces - as not yet needed.
  31.  
  32.                 Enumeration<InetAddress> adrs = nif.getInetAddresses();
  33.                 while (adrs.hasMoreElements())
  34.                 {
  35.                     InetAddress adr = adrs.nextElement();
  36.                     if (adr != null && !adr.isLoopbackAddress() && (nif.isPointToPoint() || !adr.isLinkLocalAddress()))
  37.                     {
  38.                         listAdr.add(adr);
  39.                     }
  40.                 }
  41.             }
  42.             return listAdr;
  43.         }
  44.         catch (SocketException ex)
  45.         {
  46.             Logger.getLogger(Net.class.getName()).log(Level.WARNING, "No IP address available", ex);
  47.             return listAdr;
  48.         }
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement