1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.util;
18
19 import java.net.InetAddress;
20 import java.net.NetworkInterface;
21 import java.net.SocketException;
22 import java.net.UnknownHostException;
23 import java.util.Enumeration;
24
25 import org.apache.logging.log4j.Logger;
26 import org.apache.logging.log4j.status.StatusLogger;
27
28
29
30
31 public final class NetUtils {
32
33 private static final Logger LOGGER = StatusLogger.getLogger();
34
35 private NetUtils() {
36 }
37
38
39
40
41
42
43
44
45 public static String getLocalHostname() {
46 try {
47 final InetAddress addr = InetAddress.getLocalHost();
48 return addr.getHostName();
49 } catch (final UnknownHostException uhe) {
50 try {
51 final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
52 while (interfaces.hasMoreElements()) {
53 final NetworkInterface nic = interfaces.nextElement();
54 final Enumeration<InetAddress> addresses = nic.getInetAddresses();
55 while (addresses.hasMoreElements()) {
56 final InetAddress address = addresses.nextElement();
57 if (!address.isLoopbackAddress()) {
58 final String hostname = address.getHostName();
59 if (hostname != null) {
60 return hostname;
61 }
62 }
63 }
64 }
65 } catch (final SocketException se) {
66 LOGGER.error("Could not determine local host name", uhe);
67 return "UNKNOWN_LOCALHOST";
68 }
69 LOGGER.error("Could not determine local host name", uhe);
70 return "UNKNOWN_LOCALHOST";
71 }
72 }
73
74 }