Skip to content

Instantly share code, notes, and snippets.

@viiiprock
Created November 8, 2017 05:45
Show Gist options
  • Select an option

  • Save viiiprock/c9417dcfe22380b1b74cc69c3354d05c to your computer and use it in GitHub Desktop.

Select an option

Save viiiprock/c9417dcfe22380b1b74cc69c3354d05c to your computer and use it in GitHub Desktop.
Check user IP address via webkitRTCPeerConnection
/**
* Get the user IP throught the webkitRTCPeerConnection
* @param {Function} onNewIP listener function to expose the IP locally
* @return undefined
*/
const getUserIP = (onNewIP) => { // onNewIp - your listener function for new IPs
//compatibility for firefox and chrome
let myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let pc = new myPeerConnection({iceServers: [] }),
noop = () => {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
const iterateIP = ip => {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
//create a bogus data channel
pc.createDataChannel("");
// create offer and set local description
pc.createOffer(sdp => {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop);
//listen for candidate events
pc.onicecandidate = ice => {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
// Usage
// getUserIP(ip => console.log(ip));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment