Skip to content

Instantly share code, notes, and snippets.

@leaysgur
Created June 6, 2018 07:38
Show Gist options
  • Save leaysgur/625f23571b90bcd45e9d0df741b67861 to your computer and use it in GitHub Desktop.
Save leaysgur/625f23571b90bcd45e9d0df741b67861 to your computer and use it in GitHub Desktop.
Minimum function to get local IP address.
function getLocalIP() {
let ip;
return new Promise(async (resolve, reject) => {
const pc = new RTCPeerConnection({});
pc.createDataChannel('dummy');
pc.addEventListener('icecandidate', ev => {
if (!ev.candidate) {
pc.close();
ip ? resolve(ip) : reject(new Error('IP not found'));
}
else {
const match = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.exec(ev.candidate.candidate);
match && (ip = match[0]);
}
}, false);
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
});
};
getLocalIP().then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment