package cn.hnthyy.thmz.Utils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
 
/**
* 获取MAC地址
* @author
* 2011-12
*/
public class MacAddressUtil {
    private static final String UNKNOWN="unknown";
   public static String callCmd(String[] cmd) { 
     String result = ""; 
     String line = ""; 
     try { 
       Process proc = Runtime.getRuntime().exec(cmd); 
       InputStreamReader is = new InputStreamReader(proc.getInputStream()); 
       BufferedReader br = new BufferedReader (is); 
       while ((line = br.readLine ()) != null) { 
       result += line; 
       } 
     } 
     catch(Exception e) { 
       e.printStackTrace(); 
     } 
     return result; 
   }
 
   /** 
   * 
   * @param cmd 第一个命令 
   * @param another 第二个命令 
   * @return  第二个命令的执行结果 
   */
   public static String callCmd(String[] cmd,String[] another) { 
     String result = ""; 
     String line = ""; 
     try { 
       Runtime rt = Runtime.getRuntime(); 
       Process proc = rt.exec(cmd); 
       proc.waitFor(); //已经执行完第一个命令，准备执行第二个命令 
       proc = rt.exec(another); 
       InputStreamReader is = new InputStreamReader(proc.getInputStream()); 
       BufferedReader br = new BufferedReader (is); 
       while ((line = br.readLine ()) != null) { 
         result += line; 
       } 
     } 
     catch(Exception e) { 
       e.printStackTrace(); 
     } 
     return result; 
   }
 
 
 
   /** 
   * 
   * @param ip 目标ip,一般在局域网内 
   * @param sourceString 命令处理的结果字符串 
   * @param macSeparator mac分隔符号 
   * @return mac地址，用上面的分隔符号表示 
   */
   public static String filterMacAddress(final String ip, final String sourceString,final String macSeparator) { 
     String result = ""; 
     String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})"; 
     Pattern pattern = Pattern.compile(regExp); 
     Matcher matcher = pattern.matcher(sourceString); 
     while(matcher.find()){ 
       result = matcher.group(1); 
       if(sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { 
         break; //如果有多个IP,只匹配本IP对应的Mac. 
       } 
     }
 
     return result; 
   }
 
 
 
   /** 
   * 
   * @param ip 目标ip 
   * @return  Mac Address 
   * 
   */
   public static String getMacInWindows(final String ip){ 
     String result = ""; 
     String[] cmd = { 
         "cmd", 
         "/c", 
         "ping " + ip 
         }; 
     String[] another = { 
         "cmd", 
         "/c", 
         "arp -a"
         }; 
 
     String cmdResult = callCmd(cmd,another); 
     result = filterMacAddress(ip,cmdResult,"-"); 
 
     return result; 
   } 
 
   /** 
   * @param ip 目标ip 
   * @return  Mac Address 
   * 
   */
   public static String getMacInLinux(final String ip){ 
     String result = ""; 
     String[] cmd = { 
         "/bin/sh", 
         "-c", 
         "ping " + ip + " -c 2 && arp -a"
         }; 
     String cmdResult = callCmd(cmd); 
     result = filterMacAddress(ip,cmdResult,":"); 
 
     return result; 
   } 
 
   /**
   * 获取MAC地址 
   * @return 返回MAC地址
   */
   public static String getMacAddress(String ip){
     String macAddress = "";
     macAddress = getMacInWindows(ip).trim();
     if(macAddress==null||"".equals(macAddress)){
       macAddress = getMacInLinux(ip).trim();
     }
     return macAddress;
   }

    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static 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 "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

 
   //做个测试
   public static void main(String[] args) {      
     System.out.println(getMacAddress("220.181.111.148"));
   }





//    /**
//     * 获取真实IP地址
//     * <p>使用getRealIP代替该方法</p>
//     * @param request req
//     * @return ip
//     */
//    @Deprecated
//    public static String getIpAddr(HttpServletRequest request) {
//        // 获取客户端ip地址
//        String clientIp = request.getHeader("x-forwarded-for");
//        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getHeader("Proxy-Client-IP");
//        }
//        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getRemoteAddr();
//        }
//        /*
//         * 对于获取到多ip的情况下，找到公网ip.
//         */
//        String sIP = null;
//        if (clientIp != null && !clientIp.contains("unknown") && clientIp.indexOf(",") > 0) {
//            String[] ipsz = clientIp.split(",");
//            for (String anIpsz : ipsz) {
//                if (!isInnerIP(anIpsz.trim())) {
//                    sIP = anIpsz.trim();
//                    break;
//                }
//            }
//            /*
//             * 如果多ip都是内网ip，则取第一个ip.
//             */
//            if (null == sIP) {
//                sIP = ipsz[0].trim();
//            }
//            clientIp = sIP;
//        }
//        if (clientIp != null && clientIp.contains("unknown")){
//            clientIp =clientIp.replaceAll("unknown,", "");
//            clientIp = clientIp.trim();
//        }
//        if ("".equals(clientIp) || null == clientIp){
//            clientIp = "127.0.0.1";
//        }
//        return clientIp;
//    }
//
//    /**
//     * 判断IP是否是内网地址
//     * @param ipAddress ip地址
//     * @return 是否是内网地址
//     */
//    public static boolean isInnerIP(String ipAddress) {
//        boolean isInnerIp;
//        long ipNum = getIpNum(ipAddress);
//        /**
//         私有IP：A类  10.0.0.0-10.255.255.255
//         B类  172.16.0.0-172.31.255.255
//         C类  192.168.0.0-192.168.255.255
//         当然，还有127这个网段是环回地址
//         **/
//        long aBegin = getIpNum("10.0.0.0");
//        long aEnd = getIpNum("10.255.255.255");
//
//        long bBegin = getIpNum("172.16.0.0");
//        long bEnd = getIpNum("172.31.255.255");
//
//        long cBegin = getIpNum("192.168.0.0");
//        long cEnd = getIpNum("192.168.255.255");
//        isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd)
//                || ipAddress.equals("127.0.0.1");
//        return isInnerIp;
//    }
//    private static long getIpNum(String ipAddress) {
//        String[] ip = ipAddress.split("\\.");
//        long a = Integer.parseInt(ip[0]);
//        long b = Integer.parseInt(ip[1]);
//        long c = Integer.parseInt(ip[2]);
//        long d = Integer.parseInt(ip[3]);
//        return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
//    }
//
//    private static boolean isInner(long userIp, long begin, long end) {
//        return (userIp >= begin) && (userIp <= end);
//    }
//    public static String getRealIP(HttpServletRequest request){
//        // 获取客户端ip地址
//        String clientIp = request.getHeader("x-forwarded-for");
//        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getRemoteAddr();
//        }
//        String[] clientIps = clientIp.split(",");
//        if(clientIps.length <= 1) return clientIp.trim();
//        // 判断是否来自CDN
//        if(isComefromCDN(request)){
//            if(clientIps.length>=2) return clientIps[clientIps.length-2].trim();
//        }
//        return clientIps[clientIps.length-1].trim();
//    }
//    private static boolean isComefromCDN(HttpServletRequest request) {
//        String host = request.getHeader("host");
//        return host.contains("www.189.cn") ||host.contains("shouji.189.cn") || host.contains(
//                "image2.chinatelecom-ec.com") || host.contains(
//                "image1.chinatelecom-ec.com");
//    }
 
}




