Java Host Name Get getHostInformation()

Here you can find the source of getHostInformation()

Description

Return a string identifiying this host/user/JVM.

License

Apache License

Declaration

public static String getHostInformation() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern PID_MATCHER = Pattern.compile("(\\d+)@.*");

    /**//from  w ww.j  av  a 2  s .  co  m
     * Return a string identifiying this host/user/JVM.
     */
    public static String getHostInformation() {
        // find the hostname
        String hostname = "unknown";
        final InetAddress host;
        try {
            host = InetAddress.getLocalHost();
            hostname = host.getHostName();
            hostname = hostname.replaceAll("\\..*", "");
        } catch (Exception ignore) {
            // SWALLOWED
        }
        // find the user name
        final String userName = System.getProperty("user.name");
        // and add these to the message
        return userName + "@" + hostname + " " + (getPid() != -1 ? "(" + getPid() + ")" : "");
    }

    /**
     * Return the process id of this java virtual machine.  This
     * should only be used in an advisory context (error/log messages, etc), because obtaining
     * this depends on JVM vendor specific functionality.
     *
     * @return a process id for the current JVM.
     */
    public static int getPid() {
        // WARNING: this is vendor specific... oh well...

        final String pidstr = ManagementFactory.getRuntimeMXBean().getName();
        if (pidstr == null || pidstr.length() == 0) {
            return -1;
        }
        final Matcher m = PID_MATCHER.matcher(pidstr);
        if (!m.lookingAt()) {
            return -1;
        }
        try {
            return Integer.parseInt(m.group(1));
        } catch (Exception e) {
            // SWALLOWED: won't happen...
        }
        return -1;
    }
}

Related

  1. getHost(String host)
  2. getHost(String link)
  3. getHost(String s)
  4. getHostCore(final String quadGraph)
  5. getHostGateway()
  6. getHostMac(String host)
  7. getHostName()
  8. getHostName()
  9. getHostName()