0%

获取本机ip的两种方式

文章字数:416,阅读全文大约需要1分钟

获取服务器ip,之前一直用request.getHeader("Host")获取。后来发现本机访问时获取到的是127.0.0.1这个地址,而我需要的是其它地方也能访问到的地址。

方法

  1. 解析HostName获取,直接InetAddress.getLocalHost().getHostAddress()

  2. 遍历网卡的地址(即本机所有ip地址),从中找到符合规则的。

代码

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
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.*;
import java.util.function.Function;

import org.apache.commons.lang3.StringUtils;

/**
* @author colin.cheng
* @date
*/
public class test {
/**
* 两种方法,单网卡直接获取,多网卡选择获取
*
* @param args
* @throws Exception
*/
public static void main(String[] args) {
// 1. 单网卡时,通过解析本机hostName获取ip地址
try {
InetAddress inet = InetAddress.getLocalHost();
String ipAddress = inet.getHostAddress();
System.out.println("单网卡获取ip地址 = " + ipAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}

// 2. 多网卡状态下从所有的网卡ip中找出需要的ip
// 这里的逻辑是能找到外网地址返回外网,不能找到返回最后一个内网地址
try {
String serverIp = getServerIpv4Address(ip -> {
// 本机地址过滤
if (StringUtils.equals("127.0.0.1", ip.trim())) {
return 0;
}
// 内网地址权重1
if (ip.matches(
"^(127\\.0\\.0\\.1)|(localhost)|(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$")) {
return 1;
}
// 外网地址权重2
return 2;
});

System.out.println("遍历网卡地址选取ip = " + serverIp);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 通过网卡查找网卡绑定的ipv4地址,并交由filter进行权重判断
*
* @param filter
* 自定义选择逻辑
* @return 返回权重最大的ip
* @throws Exception
*/
private static String getServerIpv4Address(Function<String, Integer> filter) throws Exception {
Map<Integer, String> resMap = new HashMap<>();
// 获得本机的所有网络接口
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
// 获得与该网络接口绑定的 IP 地址,一般只有一个
Enumeration<InetAddress> addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// 只关心 IPv4 地址
if (addr instanceof Inet4Address) {
String ip = addr.getHostAddress();
// 自定义过滤器,返回权重。
Integer index = filter.apply(ip);
if (index != 0) {
resMap.put(index, ip);
}
}
}
}
Collection<Integer> collection = resMap.keySet();
if (collection.size() > 0) {
Integer i = Collections.max(collection);
return resMap.get(i);
}
// 没有匹配结果
return null;
}
}