If it was set by a previous call sethostid(long int id), it will be in HOSTIDFILE, usually /etc/hostid.
If this is not the case, you will get the host name. You pull out the address for the host name, and if this is IPv4, it is an IPv4 address formatted in decimal to binary with the upper 16 bits, and the lower 16 bits are replaced.
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");
}
source
share