Detecting the current IP through chrome extension?

后端 未结 3 1078
情书的邮戳
情书的邮戳 2021-01-15 01:54

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?

相关标签:
3条回答
  • 2021-01-15 02:14

    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 讨论(0)
  • 2021-01-15 02:17

    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

    0 讨论(0)
  • 2021-01-15 02:29

    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);
    
    0 讨论(0)
提交回复
热议问题