gpt4 book ai didi

java - 将 Unix hostid 获取到 Java

转载 作者:IT王子 更新时间:2023-10-29 00:36:46 26 4
gpt4 key购买 nike

如何通过某种调用将 unix hostid 导入 Java?

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

最佳答案

如果它是通过先前调用 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");
}

关于java - 将 Unix hostid 获取到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6461046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com