Created
June 6, 2018 07:38
-
-
Save leaysgur/625f23571b90bcd45e9d0df741b67861 to your computer and use it in GitHub Desktop.
Minimum function to get local IP address.
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
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); | |
}); | |
}; |
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
getLocalIP().then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment