前端获取本地ip和外网ip

这里要强调下,我们这里是获取本机IP,局域网或者独立电脑,木有联网,若是借用网络接口,如搜狐、新浪等接口地址不行,因为木有网络。就是那种我一打开网页就直接获取了。

内网方法一:

getUserIP(){
        var $this = this
        var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
        if (RTCPeerConnection) (function () {
            var rtc = new RTCPeerConnection({iceServers:[]});
            if (1 || window.mozRTCPeerConnection) {     
                rtc.createDataChannel('', {reliable:false});
            };
            
            rtc.onicecandidate = function (evt) {
                if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
            };
            rtc.createOffer(function (offerDesc) {
                grepSDP(offerDesc.sdp);
                rtc.setLocalDescription(offerDesc);
            }, function (e) { console.warn("offer failed", e); });
            
            
            var addrs = Object.create(null);
            addrs["0.0.0.0"] = false;
            var currentIP2
            function updateDisplay(newAddr) {
              
                if (newAddr in addrs) return;
                else addrs[newAddr] = true;
                var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
                for(var i = 0; i < displayAddrs.length; i++){
                    if(displayAddrs[i].length > 16){
                        displayAddrs.splice(i, 1);
                        i--;
                    }
                    
                }
                // return displayAddrs[0];
                alert("ip" + displayAddrs[0]);
            }
     
            function grepSDP(sdp) {
                var hosts = [];
                sdp.split('\r\n').forEach(function (line, index, arr) {
                if (~line.indexOf("a=candidate")) {    
                        var parts = line.split(' '),       
                            addr = parts[4],
                            type = parts[7];
                        if (type === 'host') updateDisplay(addr);
                    } else if (~line.indexOf("c=")) {       
                        var parts = line.split(' '),
                            addr = parts[2];
                        updateDisplay(addr);
                    }
                });
            }
     
        })()
    }

内网方法二

getUserIP(onNewIP) { //  onNewIp-新IP的侦听器函数
            //兼容 firefox和 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
             });
    
             //sten 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);
             };
            //  console.log("ip1:"+ip);
        },

外网ip

//通过sohu接口查询外网ip
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script>
   console.log(returnCitySN);
</script>

你可能感兴趣的:(前端,tcp/ip,javascript)