Last active
September 1, 2016 20:54
-
-
Save mlaflamm/185de29c6c56cf5d41945a3d43ee8e26 to your computer and use it in GitHub Desktop.
Safe and ugly way to get the hostname in java
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
public String getFirstHostname() throws Exception { | |
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); | |
while (networkInterfaces.hasMoreElements()) { | |
NetworkInterface nic = networkInterfaces.nextElement(); | |
if (!nic.isLoopback() && nic.isUp()) { | |
Enumeration<InetAddress> addresses = nic.getInetAddresses(); | |
while (addresses.hasMoreElements()) { | |
InetAddress address = addresses.nextElement(); | |
if (address instanceof Inet4Address) { | |
return address.getHostName(); | |
} | |
} | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment