Search code examples
javalinuxunixuniqueidentifier

Get Unix hostid into Java


How can I get the unix hostid into Java through some sort of call?

http://linux.about.com/library/cmd/blcmdl1_hostid.htm


Solution

  • 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");
    }