Java 获取主机工具类

拿到本机 IP不是一件困难的事,但是拿到正确的就比较难了。

一、一般方式

【菜鸟教程】中直接通过 java.net.InetAddress类获取,如下:

1
2
3
4
5
6
7
8
9
10
11
12
import java.net.InetAddress;

public class Main {
public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress:
"+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}

这种方式获取的主机名没啥问题,但获取到的IP地址却有待考量:如果一台机器有多个网卡,他获取的IP是谁的呢?

事实上,上面输出的IP是我虚拟机IP地址,既不是我有线网卡的地址,也不是我无线网卡的地址。

二、推荐使用

利用 java.net.NetworkInterface 获取,提供常用的静态方法如下:

  1. getLocalHostAddress():返回本机 IP
  2. getLocalHostName():返回主机名
  3. getLocalInetAddress:返回 InetAddress
  4. isWindowsOS():判断操作系统是否是 Windows
  5. isMacOS():判断操作系统是否是 MacOS
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
public class LocalHostUtil {

private static InetAddress inetAddress;

/**
* 返回 InetAddress
* @return
*/
public static InetAddress getLocalInetAddress() {
if (inetAddress == null) {
load();
}
return inetAddress;
}

/**
* 返回本机IP
* @return
*/
public static String getLocalHostAddress() {
if (inetAddress == null) {
load();
}
return inetAddress.getHostAddress();
}

/**
* 返回主机名
* @return
*/
public static String getLocalHostName() {
if (inetAddress == null) {
load();
}
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return inetAddress.getHostName();
}
}

/**
* 判断操作系统是否是 Windows
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}

/**
* 判断操作系统是否是 MacOS
* @return
*/
public static boolean isMacOS() {
boolean isWindowsOS = false;
String osName = getProperty("os.name");
if (osName.toLowerCase().indexOf("mac") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}

private static InetAddress findValidateIp(List<Address> addresses) {
InetAddress local = null;
int size = addresses.size();
int maxWeight = -1;

for (int i = 0; i < size; i++) {
Address address = addresses.get(i);
if (address.isInet4Address()) {
int weight = 0;

if (address.isSiteLocalAddress()) {
weight += 8;
}

if (address.isLinkLocalAddress()) {
weight += 4;
}

if (address.isLoopbackAddress()) {
weight += 2;
}

if (address.hasHostName()) {
weight += 1;
}

if (weight > maxWeight) {
maxWeight = weight;
local = address.getAddress();
}
}
}

return local;
}

private static String getProperty(String name) {
String value = null;

value = System.getProperty(name);

if (value == null) {
value = System.getenv(name);
}

return value;
}

private static void load() {
String ip = getProperty("host.ip");

if (ip != null) {
try {
inetAddress = InetAddress.getByName(ip);
return;
} catch (Exception e) {
System.err.println(e);
// ignore
}
}

try {
List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
List<Address> addresses = new ArrayList<>();
InetAddress local = null;

try {
// 遍历网络接口
for (NetworkInterface ni : nis) {
if (ni.isUp() && !ni.isLoopback()) {
List<InetAddress> list = Collections.list(ni.getInetAddresses());
// 遍历网络地址
for (InetAddress address : list) {
addresses.add(new Address(address, ni));
}
}
}
local = findValidateIp(addresses);
} catch (Exception e) {
// ignore
}
inetAddress = local;
} catch (SocketException e) {
// ignore it
}
}

static class Address {
private InetAddress inetAddress;

private boolean loopback;

public Address(InetAddress address, NetworkInterface ni) {
inetAddress = address;

try {
if (ni != null && ni.isLoopback()) {
loopback = true;
}
} catch (SocketException e) {
// ignore it
}
}

public InetAddress getAddress() {
return inetAddress;
}

public boolean hasHostName() {
return !inetAddress.getHostName().equals(inetAddress.getHostAddress());
}

public boolean isLinkLocalAddress() {
return !loopback && inetAddress.isLinkLocalAddress();
}

public boolean isLoopbackAddress() {
return loopback || inetAddress.isLoopbackAddress();
}

public boolean isSiteLocalAddress() {
return !loopback && inetAddress.isSiteLocalAddress();
}

public boolean isInet4Address(){
return inetAddress instanceof Inet4Address;
}
}
}

【Github 示例代码】

更多 Java 笔记,详见【Java 知识笔记本】,欢迎提供想法建议。

Van wechat
最新文章,欢迎您扫一扫上面的微信公众号!
-------------    本文结束  感谢您的阅读    -------------