InetAddress.getLocalHost() returns the host server IP. To get the client´s IP address use: request.getRemoteAddr (), this method is effective in most cases. But in the Apache, Squid reverse proxy software cannot get real IP address of the client. If you use a reverse proxy software, using request.getRemoteAddr () method to get the IP address is: 127.0.0.1 or 192.168.1.110, but this is not the real IP of the client.
But we can check HTTP request header to track the original client IP address and the original client requests the server address. When we visit index.jsp/, In fact, we are not true to the browser to access the index.jsp file on the server, But the proxy server to access the index.jsp, The proxy server will access to the results returned to the browser, Because it is a proxy server to access the index.jsp, So the index.jsp through the request.getRemoteAddr () method to obtain the IP is actually the address of proxy server, Not the IP address of the client.
Method to obtain the real IP address of the client:
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader("x-forwarded-for") == null) {
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
Method for obtaining client real IP address two:
public 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");
}
else if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
else if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
However, It´ll return multiple values, but which is the real end user´s IP?
The answer is the first non unknown effective IP string in X-Forwarded-For. Such as: X-Forwarded-For: 192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
The real IP: 192.168.1.110
Access to the client MAC address:
--------------------------------------------------------------------------
Invoking the window command, through the IP to get the MAC address in the background in Bean. Methods are as follows:
public String getMACAddress(String ip){
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i <100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
return macAddress;
}
2