将 Unix hostid 获取到 Java 中

发布于 2024-11-17 04:40:42 字数 186 浏览 3 评论 0原文

如何通过某种调用将 unix hostid 转换为 Java?

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

风启觞 2024-11-24 04:40:42

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

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");
}
萝莉病 2024-11-24 04:40:42

恐怕你必须编写 JNI(或 JNA)。

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

不语却知心 2024-11-24 04:40:42

调用 Runtime.exec(String) 其中参数是“hostid”可执行文件的路径,然后排出生成的 Process 对象并将标准输出流的内容作为字符串值。

这个简单的类演示了如何实现此策略(但需要改进错误处理 [例如 stderr、异常] 和 OOP 最佳实践 [例如返回具有 bean 属性的对象等]):

public class RunCommand {
  public static String exec(String command) throws Exception {
    Process p = Runtime.getRuntime().exec(command);
    String stdout = drain(p.getInputStream());
    String stderr = drain(p.getErrorStream());
    return stdout; // TODO: return stderr also...
  }
  private static String drain(InputStream in) throws IOException {
    int b = -1;
    StringBuilder buf = new StringBuilder();
    while ((b=in.read()) != -1) buf.append((char) b);
    return buf.toString();
  }
}

您的程序可以这样使用它:

String myHostId = RunCommand.exec("/usr/bin/hostid").trim();

请注意,使用 ProcessBuilder 创建如果您的命令需要参数或环境等,Process 可能比 Runtime.exec() 更合适。

Call Runtime.exec(String) where the argument is the path to the "hostid" executable then, drain both streams of the resulting Process object and take the contents of the standard output stream as your string value.

This simple class demonstrates how you could implement this strategy (but needs improvement for error handling [e.g. stderr, exceptions] and OOP best-practices [e.g. returning an object with bean properties, etc.]):

public class RunCommand {
  public static String exec(String command) throws Exception {
    Process p = Runtime.getRuntime().exec(command);
    String stdout = drain(p.getInputStream());
    String stderr = drain(p.getErrorStream());
    return stdout; // TODO: return stderr also...
  }
  private static String drain(InputStream in) throws IOException {
    int b = -1;
    StringBuilder buf = new StringBuilder();
    while ((b=in.read()) != -1) buf.append((char) b);
    return buf.toString();
  }
}

Your program could use it as such:

String myHostId = RunCommand.exec("/usr/bin/hostid").trim();

Note that using a ProcessBuilder to create the Process might be more appropriate than Runtime.exec() if your command needs arguments or an environment, etc.

伤感在游骋 2024-11-24 04:40:42

试试这个(当然,包装在某个类中):

import java.net.InetAddress;
import java.net.UnknownHostException;

public static String getLocalHostIP()
    throws UnknownHostException
{
    InetAddress  ip;

    ip = InetAddress.getLocalHost();
    return ip.getHostAddress();
}

该方法返回“xxx.xxx.xxx.xxx”形式的字符串。

更新

一种改进的方法是:

// Determine the IP address of the local host
public static String getLocalHostIP()
{
    try
    {
        return InetAddress.getLocalHost().getHostAddress();
    }
    catch (UnknownHostException ex)
    {
        return null;
    }
}

Try this (wrapped in some class, of course):

import java.net.InetAddress;
import java.net.UnknownHostException;

public static String getLocalHostIP()
    throws UnknownHostException
{
    InetAddress  ip;

    ip = InetAddress.getLocalHost();
    return ip.getHostAddress();
}

The method returns a string of the form "xxx.xxx.xxx.xxx".

UPDATE

An improved method is:

// Determine the IP address of the local host
public static String getLocalHostIP()
{
    try
    {
        return InetAddress.getLocalHost().getHostAddress();
    }
    catch (UnknownHostException ex)
    {
        return null;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文