I am trying to find some code example to query a STUN server to get my public IP and Port, using JavaScript. Perhaps using the server at
http://www.stunserver.org
While the STUN specification is explained here http://www.ietf.org/rfc/rfc3489.txt ( this is a long document, obviously I don't expect you to read it), I have been unable to find any code example at all, which would make my life easier. Something like
function getMyIPAndPort() {
//query stun server for it
}
Thank you
The standard listening port number for a STUN server is 3478 for UDP and TCP, and 5349 for TLS.
In its essence, STUN is a simple server-client protocol. A server using the STUN protocol will rely on both UDP and TCP protocols. These servers usually listen on port 3478.
STUN provides the mechanism to communicate with users behind a network address translation (NAT) firewall, which keeps their IP addresses private within the local network (LAN). The initiating party sends a request to the STUN server, which maintains the IP addresses of the phone or computer (for video).
you can get both local and external IP
function determineIPs() {
const pc = new RTCPeerConnection({ iceServers: [ {urls: 'stun:stun.l.google.com:19302'} ] });
pc.createDataChannel('');
pc.createOffer().then(offer => pc.setLocalDescription(offer))
pc.onicecandidate = (ice) => {
if (!ice || !ice.candidate || !ice.candidate.candidate) {
console.log("all done.");
pc.close();
return;
}
let split = ice.candidate.candidate.split(" ");
if (split[7] === "host") {
console.log(`Local IP : ${split[4]}`);
} else {
console.log(`External IP : ${split[4]}`);
}
};
}
determineIPs();
e.g. https://jsbin.com/zosayiyidu/1/edit?js,console
the STUN server is for external IP. make sure you are not behind any proxy that prevents access to stun:stun.l.google.com:19302 or use a different STUN server
Very late answer. Have a look at this mini project: https://diafygi.github.io/webrtc-ips/
It does give you the IP, but doesn't seem to give the port. However, if you look at these lines: //match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
var ip_addr = ip_regex.exec(candidate)[1];
It seems that they remove the port. I am not sure, but you can play with it to find out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With