Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Last active May 16, 2016 11:43
Show Gist options
  • Save andreasvirkus/0f47fdd9210a35a8a944b3e1ca3ada81 to your computer and use it in GitHub Desktop.
Save andreasvirkus/0f47fdd9210a35a8a944b3e1ca3ada81 to your computer and use it in GitHub Desktop.
/**
* Get user's IPs using WebRTC (if supported)
* if WebRTC is not supported, ping FreeGeoIP.net
*
* partly from: https://github.com/diafygi/webrtc-ips
*
* @param onNewIP listener function for new IPs
*/
function findIP(onNewIP) {
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
if (myPeerConnection) {
var pc = new myPeerConnection({iceServers: []}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
function ipIterate(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel(""); // create a bogus data channel
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop); // create offer and set a local description
pc.onicecandidate = function(ice) { // listen for candidate events
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
// return true;
} else {
// No WebRTC support
jQuery.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(response) {
onNewIP(response.ip);
}
});
// return false;
}
}
// Sample usage
findIP(function (ip) {
console.log('User\'s IP:', ip);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment