Get Unix Hosting in Java

How can I get unix hosting in Java through some kind of call?

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

+5
source share
5 answers

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");
}
+2
source

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

+1
source

Runtime.exec(String), "hostid", Process object .

, ( (, stderr, exceptions) (, bean ..) [error]):

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();

Note that using ProcessBuilderto create Processmay be more appropriate than Runtime.exec()if your team needs arguments or environments, etc.

+1
source

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

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 the form string "xxx.xxx.xxx.xxx".

UPDATE

Improved Method:

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

All Articles