Skip to content

Instantly share code, notes, and snippets.

@pedrouid
Last active July 18, 2020 15:53
Show Gist options
  • Save pedrouid/befbafadad13660d6bb647ce137dc188 to your computer and use it in GitHub Desktop.
Save pedrouid/befbafadad13660d6bb647ce137dc188 to your computer and use it in GitHub Desktop.
Get Local IP Address from Browser (inspired by net.ipcalf.com)
function getLocalIpAddress() {
return new Promise(function (resolve, reject) {
var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) {
var rtc = new RTCPeerConnection({iceServers: []});
if (1 || window.mozRTCPeerConnection) { // FF [and now Chrome!] needs a channel/stream to proceed
rtc.createDataChannel('', {reliable: false});
};
rtc.onicecandidate = function (evt) {
// convert the candidate to SDP so we can run it through our general parser
// see https://twitter.com/lancestout/status/525796175425720320 for details
if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { reject(new Error('WebRTC Offer Failed')) });
var addrs = Object.create(null);
var INVALID_ADDR = "0.0.0.0"
addrs[INVALID_ADDR] = false;
function grepSDP(sdp) {
var hosts = [];
if (sdp) {
sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
if (~line.indexOf("a=candidate")) { // http://tools.ietf.org/html/rfc4566#section-5.13
var parts = line.split(' '), // http://tools.ietf.org/html/rfc5245#section-15.1
addr = parts[4],
type = parts[7];
if (type === 'host' && addr !== INVALID_ADDR) {
resolve(addr)
}
} else if (~line.indexOf("c=")) { // http://tools.ietf.org/html/rfc4566#section-5.7
var parts = line.split(' '),
addr = parts[2];
if (addr !== INVALID_ADDR) {
resolve(addr)
}
}
});
}
}
} else {
reject(new Error('WebRTC not supported by this browser'))
}
})
}
@stailer
Copy link

stailer commented Nov 26, 2019

Done on Firefox but random value on Chrome like : 6f7a1346-ae1b-4ba2-b69c-e01dfc490a24.local

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment