要获取本地局域网IP,然后总是获取不到,搜了很多之后,发现是新版谷歌配置的问题,哎,做个记录吧
1.外网IP地址
index.html页面引入
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
//页面内打印
const cip = returnCitySN["cip"];
console.log(cip);//218.194.xx.xx
2.局域网IP地址
此代码感谢大神点此进入
getUserIP() {
var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection)(() => {
var rtc = new RTCPeerConnection()
rtc.createDataChannel(''); //创建一个可以发送任意数据的数据通道
rtc.createOffer(offerDesc => { //创建并存储一个sdp数据
rtc.setLocalDescription(offerDesc)
}, e => {
console.log(e)
})
rtc.onicecandidate = (evt) => { //监听candidate事件
if (evt.candidate) {
var ip_addr = evt.candidate.address
console.log(ip_addr)//获取到的本地IP,192.168.xx.xx
localStorage.setItem('ip_addr', ip_addr)
}
}
})()
else {
console.log("目前仅测试了chrome浏览器OK")
}
}
重点,注意!!!
局域网IP获取不到的问题, 是因为新版google浏览器设置了隐藏本地IP,需要我们修改设置就可以了
一:输入 chrome://flags/
二:搜索 #enable-webrtc-hide-local-ips-with-mdns
三:选择 disabled
四:重启应用