2011-10-04 356 views

回答

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); 
+0

爲什麼需要依賴第三方服務器?這不會沒有互聯網連接工作! –

+0

在撰寫本文時,Chrome不允許在擴展中訪問您的DNS設置。這已在過去5年更新。 – buzzedword

2

是的,但由於NAT你無法知道它沒有網絡請求。你可以試試我的http://external-ip.appspot.com/,我爲同一任務作出

+0

酷兄弟我要添加到我的代碼。 – Max

1

YES!您可以通過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> 

希望它能幫助!