Repository navigation
Expand file tree
/
Copy pathHostIP.java
More file actions
64 lines (61 loc) · 2.07 KB
/
Copy pathHostIP.java
File metadata and controls
64 lines (61 loc) · 2.07 KB
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
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* Created by GloryChou on 2017/7/17.
*/
public class HostIP {
/**
* 获取本机IP
* @return String
*/
public static String getLocalIp() throws UnknownHostException {
if(isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
return getLinuxLocalIp();
}
}
/**
* 判断操作系统是否是Windows
* @return
*/
private static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if(osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 在Linux系统下获取本机IP
* @return String
*/
private static String getLinuxLocalIp() {
String ip = "";
try {
for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if(!name.contains("docker") && !name.contains("lo")) {
for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if(!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if(!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
System.out.println(ipaddress);
}
}
}
}
}
} catch(SocketException ex) {
ex.printStackTrace();
}
return ip;
}
}