google-chrome - 在 chrome 扩展中获取设备的本地 IP

标签 google-chrome networking google-chrome-extension

我正在开发一个 chrome 扩展程序,它应该能够发现并与本地网络中的其他设备进行通信。要发现它们,它需要找出自己的 IP 地址以找出网络的 IP 范围以检查其他设备。我被困在如何找到本地机器的 IP 地址上(我不是在谈论本地主机,也不是在谈论暴露在互联网上的地址,而是在本地网络上的地址)。 基本上,我希望得到 ifconfig在我的 background.js 内的终端中输出.

Chrome 应用程序 API 提供 chrome.socket似乎可以做到这一点,however, it is not available for extensions .通读the API for extensions我还没有找到任何能让我找到本地 ip 的东西。

我是否遗漏了什么,或者由于某种原因这是不可能的?有没有其他方法可以发现网络上的其他设备,这也很好(因为它们会在同一个 IP 范围内),但是从 2012 年 12 月开始有传言说可能会有一个用于扩展的发现 API似乎什么都不存在。

有人有什么想法吗?

最佳答案

您可以通过 WebRTC API 获取本地 IP 地址列表(更准确地说:本地网络接口(interface)的 IP 地址)。这个 API 可以被任何 Web 应用程序(不仅仅是 Chrome 扩展程序)使用。

例子:

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

关于google-chrome - 在 chrome 扩展中获取设备的本地 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18572365/

相关文章:

google-chrome-extension - Chrome 扩展登录最佳实践

javascript - 如何防止每次调用主机时都创建该类的新实例?

html - 缩放 iframe 时 Chrome 会忽略 CSS

google-chrome - 如何链接到Chrome扩展程序中的选项页面?

sockets - 所有端口都执行相同的工作?

javascript - chrome扩展加载外部js

css - 显示元素的所有 CSS 样式,即使当前不匹配媒体查询

javascript - Google Chrome 开发者工具网络标签中的状态已完成是什么意思?

powershell - 如何测试powershell中是否有事件的网络连接?

http - 为什么请求和响应会丢失?