【问题标题】:Detecting the current IP through chrome extension?通过chrome扩展检测当前IP?
【发布时间】:2011-12-01 02:03:45
【问题描述】:

我的 Chrome 扩展程序需要知道运行它的机器的 IP 是什么(真实世界的 IP) 有没有一种简单的方法可以做到这一点?

【问题讨论】:

    标签: google-chrome google-chrome-extension ip


    【解决方案1】:

    是的,但是由于 NAT,如果没有网络请求,您将无法知道它。你可以试试我的http://external-ip.appspot.com/,这是我为同一任务制作的

    【讨论】:

      【解决方案2】:

      你总是可以使用 freegeoip 服务,我最喜欢的实现之一如下:

      var geoip = function(data){
          if (data.region_name.length > 0) {
              console.log('Your external IP:', data.ip);
          }
      }
      var el = document.createElement('script');
      el.src = 'http://freegeoip.net/json/?callback=geoip';
      document.body.appendChild(el);
      

      【讨论】:

      • 为什么需要依赖第三方服务器?如果没有互联网连接,这将无法工作!
      • 在撰写本文时,Chrome 不允许在扩展程序中访问您的 DNS 设置。这已在过去 5 年中更新。
      【解决方案3】:

      是的!您可以通过 WebRTC API 获取本地网络的 IP 地址。 您可以将此 API 用于任何 Web 应用程序,而不仅仅是 Chrome 扩展程序。

      <script>
      
      function getMyLocalIP(mCallback) {
          var all_ip = [];
      
          var RTCPeerConnection = window.RTCPeerConnection ||
              window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
      
          var pc = new RTCPeerConnection({
               iceServers: []
          });
      
          pc.createDataChannel('');
      
          pc.onicecandidate = function(e) {
      
              if (!e.candidate) {
                 mCallback(all_ip);
                  return;
              }
              var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
              if (all_ip.indexOf(ip) == -1)
                  all_ip.push(ip);
          };
          pc.createOffer(function(sdp) {
              pc.setLocalDescription(sdp);
          }, function onerror() {});
      }
      getMyLocalIP(function(ip_array) { 
          document.body.textContent = 'My Local IP addresses:\n ' + ip_array.join('\n ');
      });
      

      <body> Output here... </body>
      

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 2011-11-01
        • 1970-01-01
        • 2010-12-25
        • 1970-01-01
        • 1970-01-01
        • 2018-02-02
        • 2014-06-21
        • 2012-07-14
        • 1970-01-01
        相关资源
        最近更新 更多