开发者

Detecting the current IP through chrome extension?

开发者 https://www.devze.com 2023-04-10 23:27 出处:网络
My Chrome extenti开发者_JAVA技巧on 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? You could always use the freegeoip service, on

My Chrome extenti开发者_JAVA技巧on 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?


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


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消