浏览器获取当前ip

旧巷老猫 提交于 2020-04-06 01:56:46
function findIP(callback) {
    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
    //console.log(myPeerConnection )

    var restartConfig = { iceServers: [] };
    // var pc = new myPeerConnection({ iceServers: [] }),
    var pc = new myPeerConnection({ iceServers: [] }),
        noop = function() {},
        localIPs = {},
        ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
        key;

    function ipIterate(ip) {
        if (!localIPs[ip]) callback(ip);
        localIPs[ip] = true;
    }
    pc.setConfiguration(restartConfig);
    pc.createDataChannel("");
    pc.createOffer().then(function(sdp) {
        sdp.sdp.split('\n').forEach(function(line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(ipIterate);
        });
        pc.setLocalDescription(sdp, noop, noop);
    });
    pc.onicecandidate = function(ice) {
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
    };
}

findIP(function(ip) {
    console.log('got ip: ', ip);
});

 

如果有些浏览器不能获取出来  试试清缓存在执行上述代码 ctrl+shift+delete

如果是在内网的话,获取的是内网ip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!