Last active
November 10, 2021 14:27
-
-
Save imraheel/c237da3e2e80d15d2dd32ca94a026a20 to your computer and use it in GitHub Desktop.
Find local IP using WebRTC
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 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