使用nginx等反向代理时获取Windows版客户端真实的ip及mac地址

注意:一下代码存在两点局限性:

1.该客户端必须是Windows操作系统

2.该程序代码部署到Linux上时得不到想要的效果,获取到的ip是127.0.0.1 因此ip获取到的mac地址也不准确,有待改进.....

3.请热心的朋友留言评论,多谢指点迷津!

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import javax.servlet.http.HttpServletRequest;

public class GetIPMacByWindows {

	// proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
	/**
	* 使用nginx 反向代理后,获取客户端真实IP地址.
	* @return 客户端ip地址
	*/
	public static String getIP(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();
	    }
	    if (ip.length() > 15) {  
            String[] ips = ip.split(",");  
            for (int index = 0; index < ips.length; index++) {  
                String strIp = (String) ips[index];  
                if (!("unknown".equalsIgnoreCase(strIp))) {  
                    ip = strIp;  
                    break;  
                }  
            }
	    } 
	    return ip;
	}
	
	/**
	* 获取客户端的mac地址.
	* @return mac地址
	*/
	public static String GetMacByWindows(HttpServletRequest request) {
		//获取该客户端的真实ip
    	String realIp = getIP(request);
    	//通过ip获取客户端mac地址
    	String mac_s = getMACAddress(realIp);
		return mac_s;
   }
	 
       //通过ip获取客户端mac地址
       public static String getMACAddress(String ip){   
        String macAddr = "";   
        try {   
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);   
            InputStreamReader ir = new InputStreamReader(p.getInputStream(),"GBK");   
            LineNumberReader input = new LineNumberReader(ir);   
            for (int i = 1; i < 100; i++) {   
            	String str = input.readLine();
//              System.out.println(str);
                //获取第14行的客户端mac地址
                if (i==14) {
                	macAddr = str.split("=")[1].trim();
				}
            }   
        } catch (IOException e) {   
            e.printStackTrace(System.out);   
        }   
        return macAddr;   
    }  
 
}

3.nginx配置

                

你可能感兴趣的:(JAVA基础,Nginx相关)