1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 前端JS获取内网IP地址

前端JS获取内网IP地址

时间:2023-02-07 16:08:43

相关推荐

前端JS获取内网IP地址

标题前端JS获取内网IP地址

针对谷歌浏览器的设置,才能显出出IP

1、在chrome 浏览器地址栏中输入:chrome://flags/

2、搜索 #enable-webrtc-hide-local-ips-with-mdns 该配置 并将属性改为 disabled

3、点击relaunch 浏览器即可查看到本机的内网IP地址

//调用getIP( function (ip) {/*console.log(ip);*/alert(ip);})//获取内网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);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。