在jquery中获取本机内网IP地址可以通过WebRTC API来收集本地候选IP地址,并通过正则表达式筛选出内网IP
一:实现思路
- WebRTC获取IP:通过创建RTCPeerConnection实例,浏览器会自动收集本地网络接口的IP地址作为ICE候选。
- 筛选内网IP:从收集到的候选IP中过滤出符合IP地址
二:浏览器支持
需在支持WebRTC的现代浏览器(如Chrome、Firefox)中运行
三:代码实现
let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
if (!RTCPeerConnection) {
let win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
}
//创建实例,生成连接
let pc = new RTCPeerConnection();
//监听icecandidate事件
pc.onicecandidate = (ice) => {
if (ice.candidate) {
handleCandidate(ice.candidate.candidate);
}
};
//建立一个伪数据的通道
pc.createDataChannel('');
pc.createOffer((res) => {
pc.setLocalDescription(res);
}, () => {});
// 匹配字符串中符合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_isMatchs = candidate.match(ip_regexp);
if (!ip_isMatchs) {
console.log('IP获取失败')
} else {
let ip_isMatch = candidate.match(ip_regexp)[1];
console.log(ip_isMatch)
}
}
四:注意事项
如果获取不到IP地址的话,浏览器需要进行如下操作
如果您使用的是Chrome系列浏览器(包括360和Edge),请按以下步骤操作
- 在浏览器地址栏中输入:chrome://flags/
- 搜索 enable-webrtc-hide-local-ips-with-mdns 配置,并将此配置项改为 disabled
- 重启浏览器后再次尝试
如果您使用的是Firefox浏览器,请按以下步骤操作
- 在浏览器地址栏中输入:about:config
- 搜索 media.peerconnection.ice.obfuscate_host_addresses 配置,并将此配置项改为 false
- 重启浏览器后再次尝试
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。