Detecting the current IP through chrome extension?

孤街醉人 提交于 2019-12-30 11:13:08

问题


My Chrome extention needs to know what is the IP of the machine that it is running on (the real world IP) Is there a easy way of doing it?


回答1:


You could always use the freegeoip service, one of my favorite implementations to pull it in is as follows:

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



回答2:


Yes, but because of NAT you can not know it without network request. You can try my http://external-ip.appspot.com/, which I made for the same task




回答3:


YES! You can get the IP addresses of your local network via the WebRTC API. You can use this API for any web application not just Chrome extensions.

<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>

Hope it helps!



来源:https://stackoverflow.com/questions/7655023/detecting-the-current-ip-through-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!