Returns the hostname of the local host. - Java Network

Java examples for Network:Http

Description

Returns the hostname of the local host.

Demo Code

/*//ww w .j ava  2 s  .co m
 * Copyright (c) 2015-2016 QuartzDesk.com.
 * Licensed under the MIT license (https://opensource.org/licenses/MIT).
 */
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Arrays;

public class Main{
    public static void main(String[] argv) throws Exception{
        System.out.println(getLocalHost());
    }
    /**
     * Returns the hostname of the local host. If the host name
     * cannot be determined, this method returns an empty string.
     *
     * @return the hostname of the local host.
     */
    public static String getLocalHost() {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            return localhost.getHostName();
        } catch (UnknownHostException e) {
            return CommonConst.EMPTY_STRING;
        }
    }
}

Related Tutorials