JS获取IP、MAC网卡地址(兼容IE浏览器)

发布于:2025-02-10 ⋅ 阅读:(44) ⋅ 点赞:(0)

html文件:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>获取IP、MAC网卡地址</title>
</head>
<body onload="init();">
    <div>
        <span>内网IP地址:</span> <input type="text" id="ip" name="ip" />
    </div>
    <div>
        <span>公网IP地址:</span> <input type="text" id="publicIP" name="publicIP" />
    </div>
    <div>
        <span>Mac地址:</span> <input type="text" id="mac" name="mac" />
    </div>
</body>
    
</html>
<script src="./IPMac.js"></script>

<script language="javascript">

    function init () {
        // 获取内网IP
        getIP(function(ip){
            document.getElementById("ip").value = ip;
        });

        // 获取公网IP
        ipApi(function(ip){
            document.getElementById("publicIP").value = ip; 
        });

        // 获取Mac
        var mac  = getMac();
        document.getElementById("mac").value = mac;
    } 

</script>

js文件:

/**
*  打开浏览器权限,用于浏览器获取IP地址
*    谷歌(Chrome) 删除隐藏IP:
*      浏览器输入:chrome://flags/#enable-webrtc-hide-local-ips-with-mdns
*      把 Anonymize local IPs exposed by WebRTC 设置为 disabled ( 刷新程序,IP正常显示 )
*    eage浏览器 删除隐藏ip:
*      浏览器输入: edge://flags/#enable-webrtc-hide-local-ips-with-mdns
*      把 Anonymize local IPs exposed by WebRTC 设置为 disabled ( 刷新程序,IP正常显示 )
*    火狐(FireFox) 删除隐藏IP:
*      浏览器输入 about:config
*      搜索配置 media.peerconnection.enabled 改为false ( 刷新程序,IP正常显示 )
**/
function getIP(callback){
    var ip_dups = {};
    var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.msRTCPeerConnection;
    if(RTCPeerConnection){
        var pc = new RTCPeerConnection();
         // 建立一条数据通道, 用于发送非音频视频消息
        pc.createDataChannel("");
         // 生成一个offer,带有特定的配置信息,寻找远端匹配机器的请求
        pc.createOffer().then(function (offer) {
            pc.setLocalDescription(new RTCSessionDescription(offer));
        }).catch(function (e) {
            console.log(e);
        });
        pc.onicecandidate = function (event) {
            if (event.candidate) {
                var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
                var ip_addr = ip_regex.exec(event.candidate.candidate)[1];
                if (ip_dups[ip_addr] === undefined)
                    // 回调
                    callback(ip_addr);
  
                ip_dups[ip_addr] = true;
            }
            pc.close();
        };
    }else{
        getMac(function(ip){
            callback(ip);
        })
    }
}


// 第三方获取公网ip
function ipApi(callback){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var result = JSON.parse(xhr.responseText);
            callback && callback(result.ip);
        }
    };
    xhr.open('GET', 'https://api.ipify.org?format=json', true);
    xhr.send();
}

// 判断ie浏览器
function isIE(){
    if (!!window.ActiveXObject || "ActiveXObject" in window){
        return true;
    }else{
        return false;
    }
}

// 获取ie浏览器mac地址
function getMac(ipCallback){
    if(!isIE()){
        alert("获取Mac地址请使用IE浏览器!")
        return;
    }
    var locator = new ActiveXObject ("WbemScripting.SWbemLocator");
    var service = locator.ConnectServer(".");
    var properties = service.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled =True");
    var e = new Enumerator (properties);
    {
        var p = e.item();
        var mac = p.MACAddress;
        // IE浏览器获取IP
        var ip = p.IPAddress(0);
        ipCallback && ipCallback(ip);

        return mac
    }
}