java服務端獲得客戶端IP和MAC

java服務端獲得客戶端IP和MAC


1.概述

之前在很多博客上看到關於java服務端獲得客戶端IP和MAC,其中有關於處理localhost訪問IPv6返回ip爲0:0:0:0:0:0:0:1的問題,基本都是修改hosts文件,但是我個人按照上述方法處理後沒有解決。所以我就採用在java代碼裏通過判斷字符串localhost,將其轉成127.0.0.1來解決此問題(可能這樣解決不太好)。另外還有獲取mac地址時亂碼,我個人是通過在命令行裏直接執行nbtstat -A [ip],根據獲得的內容來進行取值的。

2.詳細代碼

代碼僅供參考,有不足之處,還望不吝指出。

public class IPAndMAC{
    public static final String MAC_ADDRESS_PREFIX01 = "MAC Address = ";
    public static final String MAC_ADDRESS_PREFIX02 = "MAC 地址 = ";
    public static final String LOOPBACK_ADDRESS = "127.0.0.1";
    public static final String IPv6Address = "0:0:0:0:0:0:0:1";

    private Map stationScreenAndIP = new HashMap<>();

    public Map getStationScreenAndIP() {
        return stationScreenAndIP;
    }

    public void setStationScreenAndIP(Map stationScreenAndIP) {
        this.stationScreenAndIP = stationScreenAndIP;
    }

    /**
     * 通過HttpServletRequest返回IP地址
     *
     * @param request HttpServletRequest
     * @return ip String
     * @throws Exception
     */
    public String getIpAddr(HttpServletRequest request) throws Exception {
        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.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //如果使用localhost訪問,對於windows IPv6會返回0:0:0:0:0:0:0:1,將其轉爲127.0.0.1
        if (IPv6Address.equals(ip)) {
            ip = LOOPBACK_ADDRESS;
        }
        return ip;
    }


    /**
     * 通過IP地址獲取MAC地址
     *
     * @param ip String,127.0.0.1格式
     * @return mac String
     * @throws Exception
     */
    public String getMACAddress(String ip) throws Exception {
        String line = "";
        String macAddress = "";
        //如果爲127.0.0.1,則獲取本地MAC地址。
        if (LOOPBACK_ADDRESS.equals(ip)) {
            InetAddress inetAddress = InetAddress.getLocalHost();
            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
            //下面代碼是把mac地址拼裝成String
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                String s = Integer.toHexString(mac[i] & 0xFF);
                sb.append(s.length() == 1 ? 0 + s : s);
            }
            //把字符串所有小寫字母改爲大寫成爲正規的mac地址並返回
            macAddress = sb.toString().trim().toUpperCase();
            return macAddress;
        }
        //獲取非本地IP的MAC地址
        Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
        InputStreamReader isr = new InputStreamReader(p.getInputStream(), "GBK");
        BufferedReader br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
            if (line != null) {
                //英文環境下,命令行執行nbtstat -A [ip] 返回結果包含"MAC Address ="
                if (line.contains(MAC_ADDRESS_PREFIX01)) {
                    macAddress = fromLineToGetMacAddress(line, MAC_ADDRESS_PREFIX01);
                }
                //中文環境下,命令行執行nbtstat -A [ip] 返回結果包含"MAC 地址 ="
                if (line.contains(MAC_ADDRESS_PREFIX02)) {
                    macAddress = fromLineToGetMacAddress(line, MAC_ADDRESS_PREFIX02);
                }
            }
        }
        br.close();
        return macAddress;
    }

    public String fromLineToGetMacAddress(String line, String MAC_ADDRESS_PREFIX) {
        String macAddress = "";
        int index = line.indexOf(MAC_ADDRESS_PREFIX);
        if (index != -1) {
            macAddress = line.substring(index + MAC_ADDRESS_PREFIX.length()).trim().toUpperCase();
        }
        return macAddress;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章