使用WebRTC获取用户IP地址的JavaScript代码
该代码通过浏览器的WebRTC技术获取用户的IP地址,并将其打印在控制台中。其中,先创建一个RTCPeerConnection对象,通过该对象获取本地IP地址。具体实现过程是:创建一个DataChannel,然后通过createOffer方法生成一个offer并将其设置为本地描述符。等到本地描述符生成后,从其中解析出SDP中的IP地址,并通过回调函数返回。最后,通过调用getIPs函数即可获取用户的IP地址。
var website = 'www.xxx.com';
function getIPs(callback){
var ip_dups = {};
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
if(!RTCPeerConnection){
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
var servers = {iceServers: [{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 ip_addr = ip_regex.exec(candidate) && ip_regex.exec(candidate)[1];
if(!ip_addr) return;
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('
');
lines.forEach(function(line){
if(line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}
getIPs(function(ip){
ip && console.log(ip);
});
原文地址: https://www.cveoy.top/t/topic/m454 著作权归作者所有。请勿转载和采集!