Java Host Name Get getHostName()

Here you can find the source of getHostName()

Description

Returns a hostname from the current host

TODO: Platform dependent

License

Apache License

Return

Either the configured host name, or the hostname of the local IP

Declaration

public static String getHostName() 

Method Source Code

//package com.java2s;
/*//from w ww.ja v  a  2  s . c om
 * Copyright (C) 2014 zulily, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.google.common.base.Splitter;

import com.google.common.collect.Iterables;

import java.net.InetAddress;

public class Main {
    public final static Splitter DOT_SPLITTER = Splitter.on('.').trimResults().omitEmptyStrings();

    /**
     * Returns a hostname from the current host
     * <p>
     * TODO: Platform dependent
     *
     * @return Either the configured host name, or the hostname of the local IP
     */
    public static String getHostName() {
        return System.getenv().containsKey("HOSTNAME")
                ? Iterables.getFirst(DOT_SPLITTER.split(System.getenv("HOSTNAME")), getInetHost())
                : getInetHost();
    }

    private static String getInetHost() {
        try {
            return Iterables.getFirst(DOT_SPLITTER.split(InetAddress.getLocalHost().getHostName()), "UNKNOWN_HOST");
        } catch (Exception e) {
            return "UNKNOWN_HOST";
        }
    }
}

Related

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