Created
October 3, 2017 07:08
-
-
Save erayarslan/da4fecb24de227f3b358c84ba5fa254d to your computer and use it in GitHub Desktop.
dotone.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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