最近一个内网项目要求web端数据请求时传输本地IP地址给服务端,找了各种方法都不行,基本都是老方法或者JS不兼容。这是参照别人方法弄了个,亲测可行。
当然要是能连外网的方法就很多了,各厂商的免费http框架都行。
// main.js
getUserIP((ip) => {
console.log("ipppp === ",ip)
//ipppp === 121.90.11.160
})
function getUserIP(callback) {
var ip_dups = {};
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
var servers = {
iceServers: [
{urls: "stun:stun.services.mozilla.com"},
{urls: "stun:stun.l.google.com:19302"},
]
};
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate){
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var hasIp = ip_regex.exec(candidate)
if (hasIp) {
var ip_addr = ip_regex.exec(candidate)[1];
if(ip_dups[ip_addr] === undefined)
callback(ip_addr);
ip_dups[ip_addr] = true;
}
}
pc.onicecandidate = function(ice){
if(ice.candidate) {
handleCandidate(ice.candidate.candidate);
}
};
pc.createDataChannel("");
pc.createOffer(function(result){
pc.setLocalDescription(result, function(){}, function(){});
}, function(){});
setTimeout(function(){
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line){
if(line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}
网友评论