001/* 002 * #%L 003 * Netarchivesuite - common 004 * %% 005 * Copyright (C) 2005 - 2014 The Royal Danish Library, the Danish State and University Library, 006 * the National Library of France and the Austrian National Library. 007 * %% 008 * This program is free software: you can redistribute it and/or modify 009 * it under the terms of the GNU Lesser General Public License as 010 * published by the Free Software Foundation, either version 2.1 of the 011 * License, or (at your option) any later version. 012 * 013 * This program is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU General Lesser Public License for more details. 017 * 018 * You should have received a copy of the GNU General Lesser Public 019 * License along with this program. If not, see 020 * <http://www.gnu.org/licenses/lgpl-2.1.html>. 021 * #L% 022 */ 023package dk.netarkivet.common.distribute.bitrepository; 024 025import java.net.InetAddress; 026import java.net.UnknownHostException; 027 028import org.apache.commons.lang.StringUtils; 029import org.slf4j.Logger; 030import org.slf4j.LoggerFactory; 031 032/** 033 * Provide the hostname of the machine on which the program is running. 034 */ 035public class HostNameUtils { 036 /** Logging mechanism. */ 037 private static Logger logger = LoggerFactory.getLogger(HostNameUtils.class); 038 039 /** 040 * disallow construction by making this private. 041 */ 042 private HostNameUtils() { 043 } 044 045 /** 046 * @return the hostname of the machine as a {@link String} 047 */ 048 public static String getHostName() { 049 try { 050 //Trying to get hostname through InetAddress 051 final InetAddress iAddress = InetAddress.getLocalHost(); 052 String hostName = iAddress.getHostName(); 053 054 //Trying to do better and get Canonical hostname 055 final String canonicalHostName = iAddress.getCanonicalHostName(); 056 057 if (StringUtils.isNotEmpty(canonicalHostName)) { 058 logger.info("Local hostname (provided by getCanonicalHostName): {}", canonicalHostName); 059 return canonicalHostName; 060 } else if (StringUtils.isNotEmpty(hostName)) { 061 logger.info("Local hostname (provided by iAddress): {}", hostName); 062 return hostName; 063 } 064 065 } catch (UnknownHostException e) { 066 logger.info("Failed finding hostname the standard Java way, returning: localhost", e); 067 } 068 return "localhost"; 069 } 070}