Skip to content

Instantly share code, notes, and snippets.

@antyakushev
Created May 6, 2016 15:00
Show Gist options
  • Save antyakushev/a5d153654e02036d81cb9aec21125bdf to your computer and use it in GitHub Desktop.
Save antyakushev/a5d153654e02036d81cb9aec21125bdf to your computer and use it in GitHub Desktop.
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