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.io.File;
20 import java.net.InetAddress;
21 import java.net.MalformedURLException;
22 import java.net.NetworkInterface;
23 import java.net.SocketException;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.net.URL;
27 import java.net.UnknownHostException;
28 import java.util.Enumeration;
29
30 import org.apache.logging.log4j.Logger;
31 import org.apache.logging.log4j.status.StatusLogger;
32
33
34
35
36 public final class NetUtils {
37
38 private static final Logger LOGGER = StatusLogger.getLogger();
39 private static final String UNKNOWN_LOCALHOST = "UNKNOWN_LOCALHOST";
40
41 private NetUtils() {
42
43 }
44
45
46
47
48
49
50
51
52 public static String getLocalHostname() {
53 try {
54 final InetAddress addr = InetAddress.getLocalHost();
55 return addr.getHostName();
56 } catch (final UnknownHostException uhe) {
57 try {
58 final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
59 while (interfaces.hasMoreElements()) {
60 final NetworkInterface nic = interfaces.nextElement();
61 final Enumeration<InetAddress> addresses = nic.getInetAddresses();
62 while (addresses.hasMoreElements()) {
63 final InetAddress address = addresses.nextElement();
64 if (!address.isLoopbackAddress()) {
65 final String hostname = address.getHostName();
66 if (hostname != null) {
67 return hostname;
68 }
69 }
70 }
71 }
72 } catch (final SocketException se) {
73 LOGGER.error("Could not determine local host name", uhe);
74 return UNKNOWN_LOCALHOST;
75 }
76 LOGGER.error("Could not determine local host name", uhe);
77 return UNKNOWN_LOCALHOST;
78 }
79 }
80
81
82
83
84
85
86 public static URI toURI(final String path) {
87 try {
88
89 return new URI(path);
90 } catch (final URISyntaxException e) {
91
92
93 try {
94 final URL url = new URL(path);
95 return new URI(url.getProtocol(), url.getHost(), url.getPath(), null);
96 } catch (MalformedURLException | URISyntaxException nestedEx) {
97 return new File(path).toURI();
98 }
99 }
100 }
101
102 }