Skip to content

Instantly share code, notes, and snippets.

@iAmGroute
Created March 23, 2019 13:02
Show Gist options
  • Save iAmGroute/4328577d0c4d75eeba209c1397edc773 to your computer and use it in GitHub Desktop.
Save iAmGroute/4328577d0c4d75eeba209c1397edc773 to your computer and use it in GitHub Desktop.
An attempt to detect NAT type with javascript and WebRTC.
// Doesn't work.
// Some NAT servers reset the port binding at new 'connections'.
let NatDetector = new (function() {
this.settings = {
server1p1: 'stun:stun1.l.google.com:19302',
server1p2: 'stun:stun1.l.google.com:19302', // TODO: change port only
server2p1: 'stun:stun2.l.google.com:19302'
// 'stun:stun.l.google.com:19302',
// 'stun:stun3.l.google.com:19302',
// 'stun:stun4.l.google.com:19302',
// 'stun:stun.services.mozilla.com:3478',
};
this.NatType = Object.freeze({
undetermined: 0,
noNat: 1,
fullCone: 2,
ipRestricted: 3,
portRestricted: 4,
symmetric: 5
});
this.candidate = undefined;
this.getNatType = function() {
let self = this;
console.log('1p1', self.candidate1p1);
console.log('1p2', self.candidate1p2);
console.log('2p1', self.candidate2p1);
};
this.getCandidate = function(server) {
let self = this;
let connection = new RTCPeerConnection({iceServers: [{urls: server}]});
connection.onicecandidate = function(ice) {
let ic = ice.candidate;
self.candidate = ic ? ic.candidate : undefined;
console.log(ic);
};
connection.createDataChannel('temp');
connection.createOffer().then(offer => connection.setLocalDescription(offer));
return new Promise(function(resolve, reject) {
setTimeout(function() {
connection.close();
resolve();
}, 500);
});
};
this.main = function() {
let self = this;
return self.getCandidate(self.settings.server1p1).then(a => {
return self.getCandidate(self.settings.server1p2);
}).then(a => {
return self.getCandidate(self.settings.server2p1);
}).then(a => {
console.log('done');
});
};
})();
NatDetector.main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment