//获取内网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);
}
然后引用
window.onload=function(){
getIP( function (ip) {
console.log(ip);
})
}
方法2
//获取内网ip
var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (
function () {
var rtc = new RTCPeerConnection({iceServers:[]});
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', {reliable:false});
};
rtc.onicecandidate = function (evt) {
if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
for(var i = 0; i < displayAddrs.length; i++){
if(displayAddrs[i].length > 16){
displayAddrs.splice(i, 1);
i--;
}
}
//打印出该设备连接的所有内网ip
console.log(displayAddrs);
//排第一个ip
console.log(displayAddrs[0]);
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line, index, arr) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})();
else{
console.log("请使用主流浏览器:chrome,firefox,opera,safari");
}