通过RTCPeerConnection接口来获取用户的IP地址

时间:2025-01-18 22:48:15
var obj = {} function getIPAddress(callback) { var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection; if (RTCPeerConnection) { var rtc = new RTCPeerConnection({ iceServsers: [] }); rtc.createDataChannel('', { reliable: false }); // 建立一条数据通道, 用于发送非音频视频消息 rtc.onicecandidate = function (evt) { // 收到icecandidate事件时的事件处理器,当一个RTCDataChannel被添加到连接时,这个事件被触发 if (evt.candidate) { grepSDP('a=' + evt.candidate.candidate); } }; var addrs = Object.create(null); addrs['0.0.0.0'] = false; var grepSDP = function (sdp) { 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); } }); }; var updateDisplay = function (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--; } } callback(displayAddrs[0]); }; rtc.createOffer(function (offerDesc) { // 生成一个offer,带有特定的配置信息,寻找远端匹配机器的请求 grepSDP(offerDesc.sdp); rtc.setLocalDescription(offerDesc); }, function (e) { throw new Error(e); }); } }; getIPAddress(function (data) { obj.ip = data; document.write(obj.ip); });