Untitled
unknown
plain_text
2 years ago
1.4 kB
5
Indexable
function getLocalIP(callback) { var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var pc = new peerConnection({iceServers:[]}); var noop = function() {}; var localIPs = {}; function ipCandidate(candidate) { var ip = (candidate.split(' ')[4]); localIPs[ip] = true; } pc.createDataChannel(""); pc.createOffer().then(function(sdp) { sdp.sdp.split('\n').forEach(function(line) { if (line.indexOf('candidate') < 0) return; ipCandidate(line); }); pc.setLocalDescription(sdp, noop, noop); }).catch(function(reason) { // An error occurred, so handle the failure to connect }); // Listen for candidate events pc.onicecandidate = function(ice) { if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(/^candidate/)) return; ipCandidate(ice.candidate.candidate); }; pc.onicegatheringstatechange = function() { if (pc.iceGatheringState === 'complete') { var ips = Object.keys(localIPs); if (ips.length > 0) { callback(ips.join(', ')); } } }; } getLocalIP(function(ip) { console.log('Local IP address is: ', ip); });
Editor is loading...