本篇文章主要介绍了JAVA如何获取客户端IP地址和MAC地址非常具有实用价值,这里整理了详细的代码,需要的朋友可以参考下
本文介绍了JAVA如何获取客户端IP地址和MAC地址 ,分享给大家,具体如下:
1.获取客户端IP地址
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | public String getIp(HttpServletRequest request) throws Exception {
String ip = request.getHeader( "X-Forwarded-For" );
if (ip != null ) {
if (!ip.isEmpty() && ! "unKnown" .equalsIgnoreCase(ip)) {
int index = ip.indexOf( "," );
if (index != - 1 ) {
return ip.substring( 0 , index);
} else {
return ip;
}
}
}
ip = request.getHeader( "X-Real-IP" );
if (ip != null ) {
if (!ip.isEmpty() && ! "unKnown" .equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr(); } |
为什么不直接使用request.getRemoteAddr();而要在之前判断两个请求头"X-Forwarded-For"和"X-Real-IP"
X-Forwarded-For: client1, proxy1, proxy2, proxy3
其中的值通过一个 逗号+空格 把多个IP地址区分开, 最左边(client1)是最原始客户端的IP地址, 代理服务器每成功收到一个请求,就把请求来源IP地址添加到右边。
所有我们只取第一个IP地址
X-Real-IP,一般只记录真实发出请求的客户端IP
解决用localhost访问ip为0:0:0:0:0:0:0:1的问题
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 | public String getIp(HttpServletRequest request) throws Exception {
String ip = request.getHeader( |