Skip to content

Instantly share code, notes, and snippets.

@mlaflamm
Last active September 1, 2016 20:54
Show Gist options
  • Save mlaflamm/185de29c6c56cf5d41945a3d43ee8e26 to your computer and use it in GitHub Desktop.
Save mlaflamm/185de29c6c56cf5d41945a3d43ee8e26 to your computer and use it in GitHub Desktop.
Safe and ugly way to get the hostname in java
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