-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
NetUtil.java
86 lines (77 loc) · 3.15 KB
/
NetUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package liquibase.util;
import liquibase.Scope;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class NetUtil {
/**
* Smarter way to get localhost than InetAddress.getLocalHost. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037
*/
private static InetAddress getLocalHost() throws UnknownHostException, SocketException {
// Windows Vista returns the IPv6 InetAddress using this method, which is not
// particularly useful as it has no name or useful address, just "0:0:0:0:0:0:0:1".
// That is why windows should be treated differently to linux/unix and use the
// default way of getting the localhost.
String osName = System.getProperty("os.name");
if ((osName != null) && (osName.toLowerCase().contains("windows") ||osName.toLowerCase().contains("mac"))) {
return InetAddress.getLocalHost();
}
InetAddress loopback = null;
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface i = e.nextElement();
if (i.isUp() && !i.isPointToPoint()) {
Enumeration<InetAddress> ie = i.getInetAddresses();
while (ie.hasMoreElements()) {
InetAddress lch = ie.nextElement();
if (lch.isLoopbackAddress()) {
loopback = lch;
} else if (!lch.isLinkLocalAddress()) {
return lch;
}
}
}
}
return loopback;
}
/**
* Returns Local Host IP Address
* @return local Host IP address
* @throws UnknownHostException
* @throws SocketException
*/
public static String getLocalHostAddress() throws UnknownHostException, SocketException {
try {
InetAddress localhost = getLocalHost();
if (localhost != null) {
return localhost.getHostAddress();
}
Scope.getCurrentScope().getLog(NetUtil.class).fine("Error getting hostname. Unable to determine address for localhost");
return "unknown";
} catch (Exception e) {
Scope.getCurrentScope().getLog(NetUtil.class).fine("Error getting hostname", e);
return "unknown";
}
}
/**
* Returns Local Host Name
* @return local Host Name
* @throws UnknownHostException
* @throws SocketException
*/
public static String getLocalHostName() throws UnknownHostException, SocketException {
try {
InetAddress localhost = getLocalHost();
if (localhost != null) {
return localhost.getHostName();
}
Scope.getCurrentScope().getLog(NetUtil.class).fine("Error getting hostname. Unable to determine address for localhost");
return "unknown";
} catch (Exception e) {
Scope.getCurrentScope().getLog(NetUtil.class).fine("Error getting hostname", e);
return "unknown";
}
}
}