JS獲取本機IP地址的2種方法
1.獲取本機IP地址方法1:
if(typeof window != 'undefined'){
? ? var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
? ? if (RTCPeerConnection) (()=>{
? ? ? ? var rtc = new RTCPeerConnection()
? ? ? ? rtc.createDataChannel(''); //創(chuàng)建一個可以發(fā)送任意數(shù)據(jù)的數(shù)據(jù)通道
? ? ? ? rtc.createOffer( offerDesc => { //創(chuàng)建并存儲一個sdp數(shù)據(jù)
? ? ? ? rtc.setLocalDescription(offerDesc)
? ? }, e => { console.log(e)})
? ? rtc.onicecandidate =(evt) => { //監(jiān)聽candidate事件
? ? ? ? if (evt.candidate) {
? ? ? ? ? ? console.log('evt:',evt.candidate)
? ? ? ? ? ? let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
? ? ? ? ? ? var ip_addr = ip_rule.exec(evt.candidate.candidate)[1]
? ? ? ? ? ? console.log('ip_addr:',ip_addr) ? //打印獲取的IP地址
? ? ? ? }}
? ? })()
? ? else{console.log("沒有找到")}
}2.獲取本機IP地址方法2
//獲取用戶本地ip的方法
const getUserIP= (onNewIP)=> {
let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let pc = new MyPeerConnection({
iceServers: []
});
let noop = () => {
};
let localIPs = {};
let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
let iterateIP = (ip) => {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
};
pc.createDataChannel('');
pc.createOffer().then((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((reason) => {
});
pc.onicecandidate = (ice) => {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
getUserIP((ip) => {
state.ip=ip
console.log(ip)
console.log(state.ip)
});如果電腦沒獲取到,基本上是因為瀏覽器限制了,解除方法如下:
解決方案:
- 火狐(FireFox) 刪除隱藏IP
瀏覽器輸入 about:config
搜索配置 media.peerconnection.enabled 改為false ( 刷新程序,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正常顯示 )
總結
到此這篇關于JS獲取本機IP地址的2種方法的文章就介紹到這了,更多相關JS獲取本機IP地址內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript 使用for循環(huán)時該注意的問題-附問題總結
所謂for循環(huán)就是重復的執(zhí)行一段代碼,for循環(huán)也是希望在創(chuàng)建循環(huán)時常會用到的工具,這篇內容主要給大家介紹javascript 使用for循環(huán)時該注意的問題-附問題總結,需要的朋友可以參考下2015-08-08
JS 使用 window對象的print方法實現(xiàn)分頁打印功能
這篇文章主要介紹了JS 使用 window對象的print方法實現(xiàn)分頁打印功能,這種方法兼容性比較好,在ie和火狐瀏覽器下都可以正常使用,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-05
javascript實現(xiàn)遮罩層動態(tài)效果實例
這篇文章主要介紹了javascript實現(xiàn)遮罩層動態(tài)效果,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05

