NetUtils @author yutianbao
| 26 | * @author yutianbao |
| 27 | */ |
| 28 | public abstract class NetUtils { |
| 29 | |
| 30 | /** |
| 31 | * Pre-loaded local address |
| 32 | */ |
| 33 | public static InetAddress localAddress; |
| 34 | |
| 35 | static { |
| 36 | try { |
| 37 | localAddress = getLocalInetAddress(); |
| 38 | } catch (SocketException e) { |
| 39 | throw new RuntimeException("fail to get local ip."); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Retrieve the first validated local ip address(the Public and LAN ip addresses are validated). |
| 45 | * |
| 46 | * @return the local address |
| 47 | * @throws SocketException the socket exception |
| 48 | */ |
| 49 | public static InetAddress getLocalInetAddress() throws SocketException { |
| 50 | // enumerates all network interfaces |
| 51 | Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces(); |
| 52 | |
| 53 | while (enu.hasMoreElements()) { |
| 54 | NetworkInterface ni = enu.nextElement(); |
| 55 | if (ni.isLoopback()) { |
| 56 | continue; |
| 57 | } |
| 58 | |
| 59 | Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses(); |
| 60 | while (addressEnumeration.hasMoreElements()) { |
| 61 | InetAddress address = addressEnumeration.nextElement(); |
| 62 | |
| 63 | // ignores all invalidated addresses |
| 64 | if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) { |
| 65 | continue; |
| 66 | } |
| 67 | |
| 68 | return address; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | throw new RuntimeException("No validated local address!"); |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Retrieve local address |
| 77 | * |
| 78 | * @return the string local address |
| 79 | */ |
| 80 | public static String getLocalAddress() { |
| 81 | return localAddress.getHostAddress(); |
| 82 | } |
| 83 | |
| 84 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…