Get Unix hostid into Java Get Unix hostid into Java unix unix

Get Unix hostid into Java


If it has been set by a previous call to sethostid(long int id) it will reside in the HOSTIDFILE, typically /etc/hostid.

If it is not there, you fetch the machine's hostname. You pull out the address for the hostname, and if that's IPv4, it is the IPv4 address formatted from dotted decimal to binary with the top 16 bits and the lower 16 bits swapped.

InetAddress addr = InetAddress.getLocalHost();byte[] ipaddr = addr.getAddress();if (ipaddr.length == 4) {  int hostid = 0 | ipaddr[1] << 24 | ipaddr[0] << 16 | ipaddr[3] << 8 | ipaddr[2];  StringBuilder sb = new StringBuilder();  Formatter formatter = new Formatter(sb, Locale.US);  formatter.format("%08x", hostid);  System.out.println(sb.toString());} else {  throw new Exception("hostid for IPv6 addresses not implemented yet");}


You're going to have to write JNI (or JNA), I'm afraid.