Skip to content

Instantly share code, notes, and snippets.

@erayarslan
Created October 3, 2017 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erayarslan/da4fecb24de227f3b358c84ba5fa254d to your computer and use it in GitHub Desktop.
Save erayarslan/da4fecb24de227f3b358c84ba5fa254d to your computer and use it in GitHub Desktop.
dotone.js
var DotOne = (function () {
function DotOne(callback) {
this.iframeTrick();
this.ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
this.iceServers = [{urls: "stun:stun.services.mozilla.com"}];
this.mediaConstraints = {optional: [{RtpDataChannels: true}]};
this.ip_map = {};
this.callback = callback.bind(this);
this.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
if (!RTCPeerConnection) {
var win = iframe.contentWindow;
this.RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
}
this.get();
}
DotOne.prototype.iframeTrick = function () {
if (document.getElementById('iframe')) {
return;
}
var iframeEl = document.createElement('iframe');
iframeEl.setAttribute('sandbox', 'allow-same-origin');
iframeEl.style = 'display: none;';
iframeEl.id = 'iframe';
document.body.prepend(iframeEl);
};
DotOne.prototype.onCandidate = function (candidate) {
var ip = this.ip_regex.exec(candidate)[1];
if (this.ip_map.hasOwnProperty(ip)) {
this.callback(ip);
}
this.ip_map[ip] = true;
};
DotOne.prototype.get = function () {
var servers = {iceServers: this.iceServers};
var pc = new RTCPeerConnection(servers, this.mediaConstraints);
var onCandidate = this.onCandidate.bind(this);
pc['onicecandidate'] = function (ice) {
if (ice.candidate) {
onCandidate(ice.candidate.candidate);
}
};
pc.createDataChannel('');
pc.createOffer(function (result) {
pc.setLocalDescription(result, function () {
}, function () {
});
}, function () {
});
setTimeout(function () {
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function (line) {
if (line.indexOf('a=candidate:') === 0)
onCandidate(line);
});
}, 1000);
};
DotOne.prototype.isLocal = function (ip) {
return ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/);
};
return DotOne;
})();
new DotOne(function (ip) {
if (this.isLocal(ip)) {
console.log(ip);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment