js怎么获取本机ip地址
可以利用WEBRTC获取内网IP。
截了主要的代码,
function getIPKey(infoObj) {
var that = this;
if (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection) {
var Rtc = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
try {
var nrtc = new Rtc({
iceServers: []
});
nrtc.createDataChannel('', {
reliable: !1
});
} catch (e) {
infoObj['ip'] = '0.0.0.0';
return infoObj;
}
var e = false;
nrtc.onicecandidate = function(Rtc) {
var reg = /([0-9]{1,3}(\.[0-9]{1,3}){3})/,
infoArr = [];
'complete' != Rtc.target.iceGatheringState || e || (e = !0,
Rtc.target.localDescription.sdp.split('\n').forEach(function(a) {
if ((a = reg.exec(a)) && '127.0.0.1' != a[1] && '0.0.0.0' != a[1] && -1 === infoArr.indexOf(a[1])) {
infoArr.push(a[1]);
}
}),
(function() {
window.currentIp = 0 < infoArr.length ? infoArr.sort()[0] : '0.0.0.0';
infoObj.ip = window.currentIp;
})());
};
nrtc.createOffer(function(a) {
nrtc.setLocalDescription(a, that.F(), that.F());
}, that.F());
infoObj.ip = window.currentIp || '0.0.0.0';
return infoObj;
} else {
infoObj['ip'] = '0.0.0.0';
return infoObj;
}
}
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
本机是无法获取的,我建议通过调网上公共接口获取,给你一个我用过的例子。