001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.core.util; 018 019import java.net.InetAddress; 020import java.net.NetworkInterface; 021import java.net.SocketException; 022import java.net.UnknownHostException; 023import java.util.Enumeration; 024 025import org.apache.logging.log4j.Logger; 026import org.apache.logging.log4j.status.StatusLogger; 027 028/** 029 * 030 */ 031public final class NetUtils { 032 033 private static final Logger LOGGER = StatusLogger.getLogger(); 034 035 private NetUtils() { 036 } 037 038 /** 039 * This method gets the network name of the machine we are running on. 040 * Returns "UNKNOWN_LOCALHOST" in the unlikely case where the host name 041 * cannot be found. 042 * 043 * @return String the name of the local host 044 */ 045 public static String getLocalHostname() { 046 try { 047 final InetAddress addr = InetAddress.getLocalHost(); 048 return addr.getHostName(); 049 } catch (final UnknownHostException uhe) { 050 try { 051 final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); 052 while (interfaces.hasMoreElements()) { 053 final NetworkInterface nic = interfaces.nextElement(); 054 final Enumeration<InetAddress> addresses = nic.getInetAddresses(); 055 while (addresses.hasMoreElements()) { 056 final InetAddress address = addresses.nextElement(); 057 if (!address.isLoopbackAddress()) { 058 final String hostname = address.getHostName(); 059 if (hostname != null) { 060 return hostname; 061 } 062 } 063 } 064 } 065 } catch (final SocketException se) { 066 LOGGER.error("Could not determine local host name", uhe); 067 return "UNKNOWN_LOCALHOST"; 068 } 069 LOGGER.error("Could not determine local host name", uhe); 070 return "UNKNOWN_LOCALHOST"; 071 } 072 } 073 074}