Created
August 23, 2018 08:45
-
-
Save m-manu/d39f5cf919ee182e4307473ae1859e7c to your computer and use it in GitHub Desktop.
Some network utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NetworkUtils { | |
public static String getLocalIp() { | |
try { | |
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); | |
while (interfaces.hasMoreElements()) { | |
NetworkInterface networkInterface = interfaces.nextElement(); | |
if (networkInterface.isLoopback() || !networkInterface.isUp() || networkInterface.isVirtual() || networkInterface.isPointToPoint()) { | |
continue; | |
} | |
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); | |
while (addresses.hasMoreElements()) { | |
InetAddress address = addresses.nextElement(); | |
final String ip = address.getHostAddress(); | |
if (Inet4Address.class == address.getClass()) { | |
return ip; | |
} | |
} | |
} | |
} catch (SocketException e) { | |
throw new RuntimeException(e); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment