今天遇到了一個需求,需要獲取用戶當前的內網ip, 找了半天終於找到了方法,遂將找到的方法記錄下來,留給需要的人。
1,獲取內網ip
function getIP(callback) { let recode = {}; let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; // 如果不存在則使用一個iframe繞過 if (!RTCPeerConnection) { // 因為這里用到了iframe,所以在調用這個方法的script上必須有一個iframe標簽 // <iframe id="iframe" sandbox="allow-same-origin" style="display:none;"></iframe> let win = iframe.contentWindow; RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection; } //創建實例,生成連接 let pc = new RTCPeerConnection(); // 匹配字符串中符合ip地址的字段 function handleCandidate(candidate) { let ip_regexp = /([0-9]{1,3}(\.[0-9]{1,3}){3}|([a-f0-9]{1,4}((:[a-f0-9]{1,4}){7}|:+[a-f0-9]{1,4}){6}))/; let ip_isMatch = candidate.match(ip_regexp)[1]; if (!recode[ip_isMatch]) { callback(ip_isMatch); recode[ip_isMatch] = true; } } //監聽icecandidate事件 pc.onicecandidate = (ice) => { if (ice.candidate) { handleCandidate(ice.candidate.candidate); } }; //建立一個偽數據的通道 pc.createDataChannel(''); pc.createOffer((res) => { pc.setLocalDescription(res); }, () => {}); //延遲,讓一切都能完成 setTimeout(() => { let lines = pc.localDescription.sdp.split('\n'); lines.forEach(item => { if (item.indexOf('a=candidate:') === 0) { handleCandidate(item); } }) }, 1000); }
調用該函數:
getIP( function (ip) { console.log(ip); }) // 192.168.1.191 // 2001::2841:aa90:2843:1983:e4d1:a9b8
上面的是ipv4的,下面的是ipv6.
2,獲取公網ip
引入接口文件 <script type="text/javascript" src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
// 返回結果為 var returnCitySN = {"cip": "27.46.86.71", "cid": "440000", "cname": "廣東省"};
在下面的js中,通過調用returnCitySN.cip就可以獲取 外網的ip