当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js获取客户端IP

js获取客户端IP

2019年06月27日  | 移动技术网IT编程  | 我要评论

获取客户端公网ip

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
    document.write(returncitysn["cip"]+','+returncitysn["cname"])
</script>

 

 

获取客户端内网ip(ie不支持)

/**
 * get the user ip throught the webkitrtcpeerconnection
 * @param onnewip {function} listener function to expose the ip locally
 * @return undefined
 */
function getuserip(onnewip) { //  onnewip - your listener function for new ips
    //compatibility for firefox and chrome
    var mypeerconnection = window.rtcpeerconnection || window.mozrtcpeerconnection || window.webkitrtcpeerconnection;
    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 iterateip(ip) {
        if (!localips[ip]) onnewip(ip);
        localips[ip] = true;
    }

     //create a bogus data channel
    pc.createdatachannel("");

    // create offer and set local description
    pc.createoffer().then(function(sdp) {
        sdp.sdp.split('\n').foreach(function(line) {
            if (line.indexof('candidate') < 0) return;
            line.match(ipregex).foreach(iterateip);
        });
        
        pc.setlocaldescription(sdp, noop, noop);
    }).catch(function(reason) {
        // an error occurred, so handle the failure to connect
    });

    //listen for candidate events
    pc.onicecandidate = function(ice) {
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipregex)) return;
        ice.candidate.candidate.match(ipregex).foreach(iterateip);
    };
}

// usage

getuserip(function(ip){
    alert("got ip! :" + ip);
});

 

原文链接:https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网