问:使用springboot启动服务。当有人访问界面时,记录客户端的IP地址。
遇到的问题:局域网中只有一个出口IP,那么如何获取局域网中每个设备的Intranet IP?例如,我的计算机和平板电脑都连接到WiFi,以访问我的部署服务的地址(通过公共网络),我会发现接口中记录的两个设备的IP是相同的。我想记录该设备的Intranet IP,但是我不知道是否可以。
答:第一种方法是选择客户端
公共字符串的真实IP地址getRemortIP(HttpServletRequest request){
if(request.getHeader(“ x-forwarded-for”)== null){
return request.getRemoteAddr();
}
返回request.getHeader(“ x-forwarded-for”);
}
第二种方法是获取客户端
公共IP的真实IP地址。String getIpAddr(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
如果上述方法还不够,则应采用以下方法:
/**
*Get the current network IP
* @param request
* @return
*/
public String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//According to the network card, get the IP configured by the machine
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//In the case of multiple agents, the first IP is the real IP of the client, and multiple IP are divided according to ','
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}