如果它已由先前的调用设置,则通常sethostid(long int id)会驻留在.HOSTIDFILE/etc/hostid
如果不存在,则获取计算机的主机名。您提取主机名的地址,如果是 IPv4,则它是从点分十进制格式转换为二进制格式的 IPv4 地址,其中高 16 位和低 16 位交换。
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");
}
Run Code Online (Sandbox Code Playgroud)