欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS獲取本機(jī)IP地址的2種方法

 更新時(shí)間:2022年09月03日 16:38:59   作者:吱夏cz  
我們?cè)陧?xiàng)目經(jīng)常遇到獲取本機(jī)IP地址的需求,下面這篇文章主要給大家介紹了關(guān)于JS獲取本機(jī)IP地址的2種方法,文中通過示例代碼介紹的非常詳細(xì),本文適合新手,需要的朋友可以參考下

1.獲取本機(jī)IP地址方法1:

if(typeof window != 'undefined'){
? ? var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
? ? if (RTCPeerConnection) (()=>{
? ? ? ? var rtc = new RTCPeerConnection()
? ? ? ? rtc.createDataChannel(''); //創(chuàng)建一個(gè)可以發(fā)送任意數(shù)據(jù)的數(shù)據(jù)通道
? ? ? ? rtc.createOffer( offerDesc => { //創(chuàng)建并存儲(chǔ)一個(gè)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.獲取本機(jī)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)
  });

如果電腦沒獲取到,基本上是因?yàn)闉g覽器限制了,解除方法如下:

解決方案:

  • 火狐(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 設(shè)置為 disabled ( 刷新程序,IP正常顯示 )

  • eage瀏覽器刪除隱藏ip

瀏覽器輸入: edge://flags/#enable-webrtc-hide-local-ips-with-mdns

把 Anonymize local IPs exposed by WebRTC 設(shè)置為 disabled ( 刷新程序,IP正常顯示 )

總結(jié)

到此這篇關(guān)于JS獲取本機(jī)IP地址的2種方法的文章就介紹到這了,更多相關(guān)JS獲取本機(jī)IP地址內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論