Skip to content

Instantly share code, notes, and snippets.

@pdeva
Created January 25, 2015 20:58
Show Gist options
  • Save pdeva/1a101eb6b7fab9a5c0a3 to your computer and use it in GitHub Desktop.
Save pdeva/1a101eb6b7fab9a5c0a3 to your computer and use it in GitHub Desktop.
package com.chronon.apm.utils;
import com.chronon.apm.Log;
import com.google.common.collect.Iterables;
import java.net.*;
import java.util.Collections;
import java.util.List;
public class Hostname
{
public static String getHostname()
{
try
{
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e)
{
String ipAddress = ipAddress();
if (ipAddress != null)
{
Log.logger.info("Couldnt obtain hostname. Using ip address instead");
return ipAddress;
}
}
Log.logger.info("Couldnt obtain hostname. Using localhost");
return "localhost";
}
private static String ipAddress()
{
try
{
for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces()))
{
if ((networkInterface.getName().startsWith("eth")) || (networkInterface.getName().startsWith("en")))
{
List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
if (!addresses.isEmpty())
{
//prefer ip4 address
String ipv4Address = getIpv4Address(addresses);
if (ipv4Address != null)
return ipv4Address;
//other just return the first one in the list
return Iterables.getFirst(addresses, null).getAddress().getHostAddress();
}
}
}
} catch (SocketException e)
{
}
return null;
}
private static String getIpv4Address(List<InterfaceAddress> addresses)
{
for (InterfaceAddress address : addresses)
{
InetAddress inetAddress = address.getAddress();
if (inetAddress instanceof Inet4Address)
{
return inetAddress.getHostAddress();
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment