Skip to content

Instantly share code, notes, and snippets.

@52cik
Last active September 27, 2019 15:17
Show Gist options
  • Save 52cik/c9d859d0727fb62da0af076280cf686c to your computer and use it in GitHub Desktop.
Save 52cik/c9d859d0727fb62da0af076280cf686c to your computer and use it in GitHub Desktop.
getUserIP (Promise)
/**
* Get the user IP throught the webkitRTCPeerConnection
*
* @return {Promise<string>}
*
* @see Get the client IP address with Javascript on Safari {@link https://stackoverflow.com/questions/46925857/get-the-client-ip-address-with-javascript-on-safari}
*/
function getUserIP() {
//compatibility for firefox and chrome
var myPeerConnection =
window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
var pc = new myPeerConnection({ iceServers: [] });
var noop = function() {};
var localIPs = {};
var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
var key;
var resolve;
var reject;
var promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
function iterateIP(ip) {
if (!localIPs[ip]) resolve(ip);
localIPs[ip] = true;
}
//create a bogus data channel
pc.createDataChannel('');
// create offer and set local description
pc.createOffer()
.then(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
})
.catch(reject);
//listen for candidate events
pc.onicecandidate = function(ice) {
if (
!ice ||
!ice.candidate ||
!ice.candidate.candidate ||
!ice.candidate.candidate.match(ipRegex)
) {
return;
}
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
return promise;
}
// Usage
getUserIP().then(ip => console.log(ip));
@ashikiqbal
Copy link

Not working in Chrome 77

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment