Skip to content

Instantly share code, notes, and snippets.

@imraheel
Last active November 10, 2021 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imraheel/c237da3e2e80d15d2dd32ca94a026a20 to your computer and use it in GitHub Desktop.
Save imraheel/c237da3e2e80d15d2dd32ca94a026a20 to your computer and use it in GitHub Desktop.
Find local IP using WebRTC
const findLocalIP = () => {
return new Promise((resolve, reject) => {
// 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]) resolve(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)
}
});
}
// example usage
findLocalIP()
.then(ip => {
console.log(ip);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment