getIP.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
  2. var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
  3. if (RTCPeerConnection) (function () {
  4. var rtc = new RTCPeerConnection({iceServers:[]});
  5. if (1 || window.mozRTCPeerConnection) { // FF [and now Chrome!] needs a channel/stream to proceed
  6. rtc.createDataChannel('', {reliable:false});
  7. };
  8. rtc.onicecandidate = function (evt) {
  9. // convert the candidate to SDP so we can run it through our general parser
  10. // see https://twitter.com/lancestout/status/525796175425720320 for details
  11. if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
  12. };
  13. rtc.createOffer(function (offerDesc) {
  14. grepSDP(offerDesc.sdp);
  15. rtc.setLocalDescription(offerDesc);
  16. }, function (e) { console.warn("offer failed", e); });
  17. var addrs = Object.create(null);
  18. addrs["0.0.0.0"] = false;
  19. function updateDisplay(newAddr) {
  20. if (newAddr in addrs) return;
  21. else addrs[newAddr] = true;
  22. var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
  23. document.getElementById('list').textContent = displayAddrs.join(" or perhaps ") || "n/a";
  24. }
  25. function grepSDP(sdp) {
  26. var hosts = [];
  27. sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
  28. if (~line.indexOf("a=candidate")) { // http://tools.ietf.org/html/rfc4566#section-5.13
  29. var parts = line.split(' '), // http://tools.ietf.org/html/rfc5245#section-15.1
  30. addr = parts[4],
  31. type = parts[7];
  32. if (type === 'host') updateDisplay(addr);
  33. } else if (~line.indexOf("c=")) { // http://tools.ietf.org/html/rfc4566#section-5.7
  34. var parts = line.split(' '),
  35. addr = parts[2];
  36. updateDisplay(addr);
  37. }
  38. });
  39. }
  40. })(); else {
  41. document.getElementById('list').innerHTML = "<code>ifconfig | grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
  42. document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
  43. }