Here you can find the source of getHostName()
public static String getHostName()
//package com.java2s; /**/*from ww w. j ava 2 s .c o m*/ * Copyright Microsoft Corp. * * 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 java.net.InetAddress; public class Main { /** * API to find the hostname. This API first checks OS type. If Windows then * tries to get hostname from computername environment variable else uses * environment variable hostname. * * In case if hostname is not found from environment variable then uses java * networking apis * */ public static String getHostName() { String hostOS = System.getProperty("os.name"); String hostName = null; // Check host Operating System and get value of hostname. if (hostOS != null && hostOS.indexOf("Win") >= 0) { hostName = System.getenv("COMPUTERNAME"); } else { // non-windows platforms hostName = System.getenv("HOSTNAME"); } // If hostname is still null , use java network apis try { if (hostName == null || hostName.isEmpty()) { hostName = InetAddress.getLocalHost().getHostName(); } } catch (Exception ex) { // catches UnknownHostException // just ignore this exception } if (hostName == null || hostName.isEmpty()) { // most probabily this // case won't happen hostName = "localhost"; } return hostName; } }