Created
May 6, 2016 15:00
-
-
Save antyakushev/a5d153654e02036d81cb9aec21125bdf 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
const findIP = (onNewIP) => { // onNewIp - your listener function for new IPs | |
// compatibility for firefox and chrome | |
const myPeerConnection = window.RTCPeerConnection || | |
window.mozRTCPeerConnection || | |
window.webkitRTCPeerConnection | |
const pc = new myPeerConnection({ iceServers: [] }) | |
const noop = () => {} | |
const localIPs = {} | |
const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g | |
const ipIterate = (ip) => { | |
if (!localIPs[ip]) onNewIP(ip) | |
localIPs[ip] = true | |
} | |
pc.createDataChannel('') // create a bogus data channel | |
pc.createOffer(sdp => { | |
sdp.sdp.split('\n').forEach(line => { | |
if (line.indexOf('candidate') < 0) return | |
line.match(ipRegex).forEach(ipIterate) | |
}) | |
pc.setLocalDescription(sdp, noop, noop) | |
}, noop) // create offer and set local description | |
pc.onicecandidate = (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) | |
} | |
} | |
const addIP = (ip) => { | |
console.log('got ip: ', ip) | |
} | |
findIP(addIP) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment