22

I am working on a chrome extension which is supposed to discover and then communicate with other devices in a local network. To discover them it needs to find out its own IP-address to find out the IP-range of the network to check for other devices. I am stuck on how to find the IP-address of the local machine (I am not talking about the localhost nor am I talking about the address that is exposed to the internet but the address on the local network). Basically, what I would love is to get what would be the ifconfig output in the terminal inside my background.js.

The Chrome Apps API offers chrome.socket which seems to be able to do this, however, it is not available for extensions. Reading through the API for extensions I have not found anything that seems to enable me to find the local ip.

Am I missing something or is this impossible for some reason? Is there any other way to discover other devices on the network, that would also do just fine (as they would be on the same IP-range) but while there are some rumors from December of 2012 that there could be a discovery API for extensions nothing seems to exist yet.

Does anybody have any ideas?

Community
  • 1
  • 1
Lukas Ruge
  • 2,204
  • 3
  • 30
  • 42
  • What if there are multiple addresses, because the machine has several local network interfaces? – Barmar Sep 02 '13 at 11:46
  • I would like to have all the adresses then, provided it is posible to get any. – Lukas Ruge Sep 02 '13 at 13:10
  • Did you get this figured out? – user417669 May 08 '14 at 13:50
  • Link to "the API for extensions" has become stale and is no longer valid. Consider updating it to: https://developer.chrome.com/docs/extensions/reference/. Links to "chrome.socket" and "background.js" are also rotten (not sure of updated equivalents). The "ifconfig" link is in German, but an English equivalent exists. https://en.wikipedia.org/wiki/Ifconfig – Wyck Mar 26 '21 at 15:48

4 Answers4

44

You can get a list of your local IP addresses (more precisely: The IP addresses of your local network interfaces) via the WebRTC API. This API can be used by any web application (not just Chrome extensions).

Example:

// Example (using the function below).
getLocalIPs(function(ips) { // <!-- ips is an array of local IP addresses.
    document.body.textContent = 'Local IP addresses:\n ' + ips.join('\n ');
});

function getLocalIPs(callback) {
    var ips = [];

    var RTCPeerConnection = window.RTCPeerConnection ||
        window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

    var pc = new RTCPeerConnection({
        // Don't specify any stun/turn servers, otherwise you will
        // also find your public IP addresses.
        iceServers: []
    });
    // Add a media line, this is needed to activate candidate gathering.
    pc.createDataChannel('');
    
    // onicecandidate is triggered whenever a candidate has been found.
    pc.onicecandidate = function(e) {
        if (!e.candidate) { // Candidate gathering completed.
            pc.close();
            callback(ips);
            return;
        }
        var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
        if (ips.indexOf(ip) == -1) // avoid duplicate entries (tcp/udp)
            ips.push(ip);
    };
    pc.createOffer(function(sdp) {
        pc.setLocalDescription(sdp);
    }, function onerror() {});
}
<body style="white-space:pre"> IP addresses will be printed here... </body>
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • This should be the accepted answer!! Works like charm! I spent all my day searching for this but everyone said to send request to www server but Thanks to @Rob W he solved it :-) – Rafique Mohammed Sep 12 '15 at 11:36
  • I see your using an ip array. Could it possibly return more than one IP, and why? Is it just for the additional IPV6 address? How can I filter out only one useful IPV4 address? is it just the first element of the array or I'll have to parse them all? – Zorgatone Feb 08 '16 at 10:54
  • 1
    @Zorgatone It could be more than 1, e.g. if you're connected via a cable, wireless, VPN, etc. Active network interfaces will show up in the list. All IP addresses are potentially useful. And note that my method only shows the local addresses (e.g. 192.168.1.1), if you're looking for a public IP address, then you have to specify a STUN server in the `iceServers` list. – Rob W Feb 08 '16 at 10:59
  • No I don't need the public one thanks. Well I'm developing a mobile application. So on mobile usually you have only one network. If there's no IPV6 address and it's only IPV4, I'll just pick the first one. Thanks! :) – Zorgatone Feb 08 '16 at 11:01
  • For some reason when i've dropped this into my code the callback isn't ever getting hit. I can break before getLocalIPs, but when I resume it just skips right past the callback function. – moodyak Feb 19 '16 at 01:08
  • Once I have my local ip address, how can I get the local ip addresses of other computers connected to the same local network ? – Dejan Bogatinovski Apr 28 '18 at 10:06
  • 1
    This gives something like "763fa077-240d-4996-941d-714b9f2b0f6f.local" instead of an IP address for me. If I switch to incognito tab it works. Turns out that you need to disable "Anonymize local IPs exposed by WebRTC" flag in chrome://flags – bhdrozgn Apr 14 '22 at 09:39
2

After some searching I've found that similar question was answered before. This API is inaccessible from extension, but available for chrome apps:

use chrome.system.network.getNetworkInterfaces.

This will return an array of all interfaces with their IP address.

This is my sample code:

chrome.system.network.getNetworkInterfaces(function(interfaces){ console.log(interfaces); });

manifest-permissions:

"permissions": [ "system.network" ], ...

Community
  • 1
  • 1
3demax
  • 136
  • 1
  • 9
  • Actually, it *is* possible to query the addresses of your local network interfaces. I've posted an example below at https://stackoverflow.com/a/29514292/938089. – Rob W Apr 08 '15 at 12:15
  • I've updated answer with proper APIs. You solution looks good, but isn't it a bug in WebRTC implementation? In firefox, execution of your snippet was prevented by NoScript detecting it as XSS attempt. – 3demax Apr 08 '15 at 17:51
  • Nope; being able to get the IP addresses is a feature of WebRTC. In order to communicate with other peers, both peers have to know each others' address. If both are on the same intranet, knowing the local addresses is sufficient. Otherwise STUN is needed to get the public IP addresses. – Rob W Apr 08 '15 at 17:55
  • 3
    This doesn't work for extensions, it gives the following error: `'system.network' is only allowed for packaged apps, but this is a extension.` – jishi Mar 14 '16 at 10:47
0
> chrome.system.network.getNetworkInterfaces(function(interfaces){
>       console.log(interfaces);    }); 

manifest-permissions:

"permissions": [ "system.network" ], ...

Works for me too and it replies:

(4) [{…}, {…}, {…}, {…}]

0 : {address: "xxxx", name: "en0", prefixLength: 64}

1 : {address: "192.168.86.100", name: "en0", prefixLength: 24}

2 : {address: "xxxx", name: "awdl0", prefixLength: 64}

3 : {address: "xxxx", name: "utun0", prefixLength: 64}

length : 4

-2

see http://developer.chrome.com/extensions/webRequest.html for detail, my code example:

// get IP using webRequest
var currentIPList = {};
chrome.webRequest.onCompleted.addListener(
  function(info) {
    currentIPList[info.url] = info.ip;
    currentIPList[info.tabId] = currentIPList[info.tabId] || [];
    currentIPList[info.tabId].push(info);
    return;
  },
  {
    urls: [],
    types: []
  },
  []
);
andy wu
  • 13
  • 1
  • 2
    As best as I can tell, this gets the IP of the remote server, not the client's own IP address. It looks like @LukasRuge is trying to get the client's IP. – Doktor J Jan 30 '15 at 19:57