在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
- 重啓瀏覽器後再次嘗試