Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. function getIPs(callback){
  2. var ip_dups = {};
  3.  
  4. //compatibility for firefox and chrome
  5. var RTCPeerConnection = window.RTCPeerConnection
  6. || window.mozRTCPeerConnection
  7. || window.webkitRTCPeerConnection;
  8. var useWebKit = !!window.webkitRTCPeerConnection;
  9.  
  10. //bypass naive webrtc blocking using an iframe
  11. if(!RTCPeerConnection){
  12. //NOTE: you need to have an iframe in the page right above the script tag
  13. //
  14. //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
  15. //<script>...getIPs called in here...
  16. //
  17. var win = iframe.contentWindow;
  18. RTCPeerConnection = win.RTCPeerConnection
  19. || win.mozRTCPeerConnection
  20. || win.webkitRTCPeerConnection;
  21. useWebKit = !!win.webkitRTCPeerConnection;
  22. }
  23.  
  24. //minimal requirements for data connection
  25. var mediaConstraints = {
  26. optional: [{RtpDataChannels: true}]
  27. };
  28.  
  29. var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
  30.  
  31. //construct a new RTCPeerConnection
  32. var pc = new RTCPeerConnection(servers, mediaConstraints);
  33.  
  34. function handleCandidate(candidate)
  35. {
  36. //match just the IP address
  37. var ip_regex = /([0-9]{1,3}(.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
  38. var ip_addr = ip_regex.exec(candidate)[1];
  39.  
  40. //remove duplicates
  41. if(ip_dups[ip_addr] === undefined)
  42. callback(ip_addr);
  43.  
  44. ip_dups[ip_addr] = true;
  45. }
  46.  
  47. //listen for candidate events
  48. pc.onicecandidate = function(ice){
  49.  
  50. //skip non-candidate events
  51. if(ice.candidate)
  52. handleCandidate(ice.candidate.candidate);
  53. };
  54.  
  55. //create a bogus data channel
  56. pc.createDataChannel("");
  57.  
  58. //create an offer sdp
  59. pc.createOffer(function(result){
  60.  
  61. //trigger the stun server request
  62. pc.setLocalDescription(result, function(){}, function(){});
  63.  
  64. }, function(){});
  65.  
  66. //wait for a while to let everything done
  67. setTimeout(function(){
  68. //read candidate info from local description
  69. var lines = pc.localDescription.sdp.split('n');
  70.  
  71.  
  72. lines.forEach(function(line){
  73. if(line.indexOf('a=candidate:') === 0)
  74. {
  75. handleCandidate(line);
  76. }
  77.  
  78. });
  79. }, 1000);
  80. }
  81.  
  82. //Test: Print the IP addresses into the console
  83. getIPs(
  84. function(ip)
  85. {
  86. alert(ip);
  87. });
  88. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement