Created
December 7, 2018 18:20
-
-
Save mataprasad/b44e246c39260549b28d53d966e5df8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example (using the function below). | |
getLocalIPs(function(ips) { // <!-- ips is an array of local IP addresses. | |
document.body.textContent = 'Local IP addresses:\n ' + ips.join('\n '); | |
}); | |
function getLocalIPs(callback) { | |
var ips = []; | |
var RTCPeerConnection = window.RTCPeerConnection || | |
window.webkitRTCPeerConnection || window.mozRTCPeerConnection; | |
var pc = new RTCPeerConnection({ | |
// Don't specify any stun/turn servers, otherwise you will | |
// also find your public IP addresses. | |
iceServers: [] | |
}); | |
// Add a media line, this is needed to activate candidate gathering. | |
pc.createDataChannel(''); | |
// onicecandidate is triggered whenever a candidate has been found. | |
pc.onicecandidate = function(e) { | |
if (!e.candidate) { // Candidate gathering completed. | |
pc.close(); | |
callback(ips); | |
return; | |
} | |
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1]; | |
if (ips.indexOf(ip) == -1) // avoid duplicate entries (tcp/udp) | |
ips.push(ip); | |
}; | |
pc.createOffer(function(sdp) { | |
pc.setLocalDescription(sdp); | |
}, function onerror() {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment