Last active
May 6, 2017 10:37
-
-
Save reqshark/eb6dfe0ac0c525778a8597d2d47fc04b to your computer and use it in GitHub Desktop.
get your ips
This file contains hidden or 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
const ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/ | |
const digits = /^\d\d\.|^\d\d\d\./g | |
const local = /^127\.|^10\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168\./g | |
const RTCPeerConnection = window.RTCPeerConnection | |
|| window.mozRTCPeerConnection || window.webkitRTCPeerConnection | |
ipaddr(function(addr1){ | |
console.log(addr1) | |
setTimeout(function(){ | |
ipaddr(function(addr2){ | |
console.log(addr2) | |
}) | |
}, 2000) | |
}) | |
function ipaddr (fn) { | |
if (RTCPeerConnection) | |
return getIps( ip => { if (ip.match(digits)) { | |
if (ip.match(local)) | |
return fn(ip, false) | |
return fn(ip, true) | |
}}) | |
noop() | |
} | |
function getIps (callback) { | |
var ip_dups = {}; | |
//compatibility for firefox and chrome | |
var useWebKit = !!window.webkitRTCPeerConnection; | |
/* minimal requirements for data connection */ | |
var mediaConstraints = { optional: [ { RtpDataChannels: true } ] } | |
var servers = { iceServers: [ { urls: 'stun:stun.services.mozilla.com' } ] } | |
var pc = new RTCPeerConnection(servers, mediaConstraints) | |
pc.onicecandidate = ice => { /* listen for candidate events */ | |
if (ice.candidate) /* skip non-candidate events */ | |
handleCandidate(ice.candidate.candidate) | |
} | |
/* create bogus data channel, offer sdp and trigger a stun server request */ | |
pc.createDataChannel('') | |
pc.createOffer(result => pc.setLocalDescription(result, noop, noop), noop) | |
setTimeout(()=> { | |
console.log(pc.localDescription) | |
}, 550) | |
setTimeout(()=> pc.localDescription.sdp.split('\n') | |
.filter(line => line.indexOf('a=candidate:') === 0) | |
.map( i => handleCandidate(i) ), 250) | |
function handleCandidate (candidate) { | |
console.log(candidate) | |
try { | |
var ip_addr = ip_regex.exec(candidate)[1] | |
if(ip_dups[ip_addr] === undefined) /* remove dups */ | |
callback(ip_addr) | |
ip_dups[ip_addr] = true; | |
} catch($) {} | |
} | |
} | |
function noop() {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment