本文介绍了JAVA如何获取客户端IP地址和MAC地址 ,分享给大家,具体如下:
1.获取客户端IP地址
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的问题
public String getIp(HttpServletRequest request) throws Exception {
String ip = request.getHeader("X-Forwarded-For");
if (ip != null) {
if (!ip.isEmpty() &&