Skip to content

Instantly share code, notes, and snippets.

@azechi
Last active April 24, 2019 01:38
Show Gist options
  • Save azechi/149d7762a5b7c5512ae043987b4aab9f to your computer and use it in GitHub Desktop.
Save azechi/149d7762a5b7c5512ae043987b4aab9f to your computer and use it in GitHub Desktop.
Find out IP Address on the public side of a NAT using public stun server
function getIPAddress() {
const S = "stun.l.google.com:19302";
return new Promise(resolve=>{
const pc = new RTCPeerConnection({
"iceServers": [{
"urls": ["stun:" + S]
}]
});
const rslt = []
pc.onicecandidate = e=>{
if (!e.candidate) {
return resolve(rslt);
}
if (e.candidate && e.candidate.candidate) {
//https://tools.ietf.org/html/rfc5245#section-15.1
const [ip,,, type] = e.candidate.candidate.split(" ", 8).slice(4);
if(type == "srflx"){
rslt.push(ip);
}
}
};
pc.onnegotiationneeded = async()=>{
await pc.setLocalDescription(await pc.createOffer())
};
pc.createDataChannel("");
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment