Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

In this page you can find the example usage for java.net InetAddress getHostName.

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:org.nebulaframework.util.system.SystemUtils.java

/**
 * Attempts to detect information about the system
 * environment and returns the information as a Map.
 * //from   w w w  .jav a 2  s. c o m
 * @param props Properties File
 * @return Map of information
 */
public static Map<String, String> detectSystemInfo() {

    Map<String, String> map = new HashMap<String, String>();

    InetAddress ipAddress = null;
    try {
        ipAddress = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        log.warn("[SystemUtils] Unable to resolve local IP Address");
    }

    map.put("os.name", System.getProperty("os.name"));
    map.put("os.arch", System.getProperty("os.arch"));
    map.put("java.version", System.getProperty("java.version"));
    map.put("java.vendor", System.getProperty("java.vendor"));
    if (ipAddress != null) {
        map.put("net.ip", ipAddress.getHostAddress());
        map.put("net.name", ipAddress.getHostName());
    } else {
        map.put("net.ip", "");
        map.put("net.name", "");
    }

    return map;
}

From source file:org.opennms.netmgt.poller.remote.support.ScanReportPollerFrontEnd.java

/**
 * Construct a list of certain system properties and metadata about this
 * monitoring system that will be relayed back to the {@link PollerBackEnd}.
 *
 * @return a {@link java.util.Map} object.
 *///from ww w . j a  v  a2  s .  c o m
public static Map<String, String> getDetails() {
    final HashMap<String, String> details = new HashMap<String, String>();
    final Properties p = System.getProperties();

    for (final Map.Entry<Object, Object> e : p.entrySet()) {
        if (e.getKey().toString().startsWith("os.") && e.getValue() != null) {
            details.put(e.getKey().toString(), e.getValue().toString());
        }
    }

    final InetAddress us = InetAddressUtils.getLocalHostAddress();
    details.put(HOST_ADDRESS_KEY, InetAddressUtils.str(us));
    details.put(HOST_NAME_KEY, us.getHostName());

    return Collections.unmodifiableMap(details);
}

From source file:hsyndicate.utils.IPUtils.java

public static Collection<String> getHostAddress() {
    if (!cachedHostAddr.isEmpty()) {
        return Collections.unmodifiableCollection(cachedHostAddr);
    } else {/*w w w  .  j  a va2 s  .c o m*/
        try {
            Enumeration e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();

                    String hostAddress = i.getHostAddress();
                    if (isProperHostAddress(hostAddress)) {
                        if (!cachedHostAddr.contains(hostAddress)) {
                            cachedHostAddr.add(hostAddress);
                        }
                    }

                    String hostName = i.getHostName();
                    if (isProperHostAddress(hostName)) {
                        if (!cachedHostAddr.contains(hostName)) {
                            cachedHostAddr.add(hostName);
                        }
                    }

                    String canonicalHostName = i.getCanonicalHostName();
                    if (isProperHostAddress(canonicalHostName)) {
                        if (!cachedHostAddr.contains(canonicalHostName)) {
                            cachedHostAddr.add(canonicalHostName);
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            LOG.error("Exception occurred while scanning local interfaces", ex);
        }

        return Collections.unmodifiableCollection(cachedHostAddr);
    }
}

From source file:SystemUtils.java

public static String GetHostname() {
    String hostname = null;/*from  www .  j  a  v  a  2 s .c om*/

    try {
        InetAddress lh = InetAddress.getLocalHost();
        hostname = lh.getHostName();
    } catch (Exception e) {
    }

    return hostname;
}

From source file:org.apache.tez.mapreduce.hadoop.MRHelpers.java

/**
 * Sets up parameters which used to be set by the MR JobClient. Includes
 * setting whether to use the new api or the old api. Note: Must be called
 * before generating InputSplits// w w w.j  av a 2  s . c  o  m
 *
 * @param conf
 *          configuration for the vertex.
 */
public static void doJobClientMagic(Configuration conf) throws IOException {
    setUseNewAPI(conf);
    // TODO Maybe add functionality to check output specifications - e.g. fail
    // early if the output directory exists.
    InetAddress ip = InetAddress.getLocalHost();
    if (ip != null) {
        String submitHostAddress = ip.getHostAddress();
        String submitHostName = ip.getHostName();
        conf.set(MRJobConfig.JOB_SUBMITHOST, submitHostName);
        conf.set(MRJobConfig.JOB_SUBMITHOSTADDR, submitHostAddress);
    }
    // conf.set("hadoop.http.filter.initializers",
    // "org.apache.hadoop.yarn.server.webproxy.amfilter.AmFilterInitializer");
    // Skipping setting JOB_DIR - not used by AM.

    // Maybe generate SHUFFLE secret. The AM uses the job token generated in
    // the AM anyway.

    // TODO eventually ACLs
    setWorkingDirectory(conf);
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.configurator.Configurator.java

/**
 * Retrieve host name, mac address of the device
 *
 * @return details Map<String, String>
 *///  w w  w  .  ja va  2s  .c om
protected static Map<String, String> getDeviceDetails() {
    InetAddress ip;
    String hostName = "";
    String macAddress = ConfigConstants.DEFAULT_MAC_ADDRESS;
    Map<String, String> details = new HashMap();
    try {
        ip = InetAddress.getLocalHost();
        hostName = ip.getHostName();
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaceEnumeration.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
            Enumeration<InetAddress> enumeration = networkInterface.getInetAddresses();
            for (; enumeration.hasMoreElements();) {
                InetAddress address = enumeration.nextElement();
                if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()
                        && address.isSiteLocalAddress()) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            //Construct mac address
                            sb.append(String.format("%02X%s", mac[i],
                                    (i < mac.length - 1) ? ConfigConstants.DELIMITER : ""));
                        }
                        macAddress = sb.toString();
                        break;
                    }
                }
            }
        }
    } catch (UnknownHostException | SocketException e) {
        log.error("Error while retrieving mac address", e);
        Runtime.getRuntime().exit(1);
    }
    details.put(ConfigConstants.HOST_NAME, hostName);
    details.put(ConfigConstants.MAC_ADDRESS, macAddress);
    return details;
}

From source file:org.rhq.plugins.apache.util.HttpdAddressUtility.java

private static void updateWithServerName(Address address, String serverName) {
    //the configuration may be invalid and/or the hostname can be unresolvable.
    //we try to match the address with the servername first by IP address
    //but if that fails (i.e. the hostname couldn't be resolved to an IP)
    //we try to simply match the hostnames themselves.

    Address serverAddr = Address.parse(serverName);
    String ipFromServerName = null;
    String ipFromAddress = null;//from  ww  w. jav  a2s .c om
    String hostFromServerName = null;
    String hostFromAddress = null;
    boolean lookupFailed = false;

    try {
        InetAddress addrFromServerName = InetAddress.getByName(serverAddr.host);
        ipFromServerName = addrFromServerName.getHostAddress();
        hostFromServerName = addrFromServerName.getHostName();
    } catch (UnknownHostException e) {
        ipFromServerName = serverAddr.host;
        hostFromServerName = serverAddr.host;
        lookupFailed = true;
    }

    try {
        InetAddress addrFromAddress = InetAddress.getByName(address.host);
        ipFromAddress = addrFromAddress.getHostAddress();
        hostFromAddress = addrFromAddress.getHostName();
    } catch (UnknownHostException e) {
        ipFromAddress = address.host;
        hostFromAddress = address.host;
        lookupFailed = true;
    }

    if (ipFromAddress.equals(ipFromServerName)
            || (lookupFailed && (hostFromAddress.equals(hostFromServerName)))) {
        address.scheme = serverAddr.scheme;
        address.host = serverAddr.host;
    }
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

static Credentials getCredentials(final String username, final String password, final InetAddress address) {
    int i = username.indexOf("\\"); //$NON-NLS-1$
    if (i > 0 && i < username.length() - 1 && address != null) {
        return new NTCredentials(username.substring(i + 1), password, address.getHostName(),
                username.substring(0, i));
    } else {/*  w w  w. j av a 2s  .  c o  m*/
        return new UsernamePasswordCredentials(username, password);
    }
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.Updater.java

public static void uploadLog(UpdateData up, String updateDir, boolean isBatch) {
    String hostname = "";
    String jvmName = "";
    String balanceLog = "Balance";
    String workerLog = "workerStep";
    String paramsFile = "params.conf";
    logPath = "Logs/workers/";

    if (up.getFTPAddress() == null)
        return;//from  w  w  w .ja  v a 2  s. c o m

    FTPIP = up.getFTPAddress().getIPaddress();
    FTPPORT = up.getFTPAddress().getPort();

    System.out.println("FPT: " + FTPIP + "PORT: " + FTPPORT);
    FTPClient client = connect(FTPIP, Integer.parseInt(FTPPORT));

    login(client);

    try {
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        //byte[] ipAddr = addr.getAddress();

        // Get hostname
        hostname = addr.getHostName();
    } catch (UnknownHostException e) {
    }

    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    //
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    jvmName = bean.getName();

    /*try {
       client.createDirectory(dateFormat.format(date)+"@"+hostname);
    } catch (IllegalStateException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (FTPIllegalReplyException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (FTPException e1) {
       isDirExists = true;
    }*/

    try {

        if (client == null)
            return;

        client.changeDirectory(updateDir);

        File blog = new File(logPath + balanceLog + jvmName + ".log");
        if (blog.exists())
            client.upload(blog);
        else
            System.out.println("File not found");

        File wlog = new File(logPath + workerLog + jvmName + ".log");
        if (wlog.exists())
            client.upload(wlog);
        else
            System.out.println("File not found");

        File params = new File(logPath + paramsFile);
        if (params.exists())
            client.upload(params);
        else
            System.out.println("File not found");

        ArrayList<File> fileToBackup = new ArrayList<File>();
        fileToBackup.add(params);
        fileToBackup.add(blog);
        fileToBackup.add(wlog);

        backupLog(updateDir, fileToBackup);
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPIllegalReplyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPDataTransferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPAbortedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.flapdoodle.embed.redis.RedisDProcess.java

public static boolean shutdownRedis(AbstractRedisConfig config) {
    try {/*from  ww w .j  a  v a 2  s.  co  m*/
        // ensure that we don't get into a stackoverflow when starting
        // the artifact fails entirely
        if (config.isNested()) {
            logger.log(Level.INFO, "Nested stop, won't execute redis process again");
            return false;
        }
        InetAddress host = config.net().getServerAddress();
        int port = config.net().getPort();
        if (!host.isLoopbackAddress()) {
            logger.log(Level.WARNING,
                    "" + "---------------------------------------\n" + "Your localhost ("
                            + host.getHostAddress() + ") is not a loopback adress\n"
                            + "We can NOT send shutdown to redis, because it is denied from remote."
                            + "---------------------------------------\n");
            return false;
        }
        try {
            Jedis j = new Jedis(host.getHostName(), port);
            String reply = j.shutdown();
            if (StringUtils.isEmpty(reply)) {
                return true;
            } else {
                logger.log(Level.SEVERE, String
                        .format("sendShutdown closing %s:%s; Got response from server %s", host, port, reply));
                return false;
            }
        } catch (JedisConnectionException e) {
            logger.log(Level.WARNING,
                    String.format("sendShutdown closing %s:%s. No Service listening on address.\n%s", host,
                            port, e.getMessage()));
            return true;
        }
    } catch (UnknownHostException e) {
        logger.log(Level.SEVERE, "sendStop", e);
    }
    return false;
}