Java Host Name Get getHostname()

Here you can find the source of getHostname()

Description

get the hostname by resolving our own address this method is not async due to possible dns call, we run this with executeBlocking

License

Open Source License

Return

the hostname

Declaration

public static String getHostname() 

Method Source Code

//package com.java2s;
/*/*from   w w  w.j  a va 2 s .c o m*/
 *  Copyright (c) 2011-2015 The original author or authors
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *       The Eclipse Public License is available at
 *       http://www.eclipse.org/legal/epl-v10.html
 *
 *       The Apache License v2.0 is available at
 *       http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

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

public class Main {
    /**
     * get the hostname by resolving our own address
     *
     * this method is not async due to possible dns call, we run this with executeBlocking
     *
     * @return the hostname
     */
    public static String getHostname() {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            return ip.getCanonicalHostName();
        } catch (UnknownHostException e) {
            // as a last resort, use localhost
            // another common convention would be to use the clients ip address
            // like [192.168.1.1] or [127.0.0.1]
            return "localhost";
        }
    }
}

Related

  1. getHostName()
  2. getHostname()
  3. getHostName()
  4. getHostname()
  5. getHostName()
  6. getHostname()
  7. getHostName()
  8. getHostname()
  9. getHostName()