Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a STUN server with JavaScript to get public IP and Port?

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

like image 531
iAteABug_And_iLiked_it Avatar asked Jun 13 '13 10:06

iAteABug_And_iLiked_it


People also ask

What is the port number used to contact a STUN server?

The standard listening port number for a STUN server is 3478 for UDP and TCP, and 5349 for TLS.

Does STUN work with TCP?

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.

What is STUN server IP?

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).


2 Answers

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

like image 164
pref Avatar answered Sep 20 '22 17:09

pref


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.

like image 41
Wessel Wessels Avatar answered Sep 21 '22 17:09

Wessel Wessels