【问题标题】:Retrieving a List of network interfaces in node.js (ioctl SIOCGIFCONF)在 node.js (ioctl SIOCGIFCONF) 中检索网络接口列表
【发布时间】:2011-12-08 06:05:13
【问题描述】:

我是 node 新手,我正在开发一个 node 应用程序,利用 node_pcap 来捕获数据包数据并用它做一些有趣的事情。捕获数据的输入之一是要监听的网络接口,即“eth0”。

我认为如果我能够以编程方式查找系统上的可用接口并将它们呈现给程序的用户并允许他们选择要收听的接口,那将是非常棒的。在 C 语言中,我会使用 SIOCGIFCONF 使用 ioctl(或带有 winsock 的 ioctlsocket)。

我的问题是,目前是否存在在节点中执行此操作的机制?我已经搜索了很多,但没有找到任何这样的解决方案。

如果此功能当前不存在,我会假设我可以使用 ioctl 在 C/C++ 中编写模块绑定来完成此操作。

感谢您的宝贵时间!

【问题讨论】:

    标签: javascript node.js interface v8 ioctl


    【解决方案1】:

    更新自节点 13.7.0 起有效

    自提交此答案以来已重命名。现在只是 networkInterfaces() 像这样:

    require('os').networkInterfaces()
    

    或者最好是这样:

    import { networkInterfaces } from 'os';
    
    const interfaces = networkInterfaces();
    

    新文档网址:https://nodejs.org/docs/latest/api/os.html#os_os_networkinterfaces

    原答案

    从 Node.js 0.6.0 开始,您拥有

    require('os').getNetworkInterfaces()
    

    http://nodejs.org/docs/latest/api/os.html#os.getNetworkInterfaces

    【讨论】:

    • 太棒了!这正是我所需要的。在我提出这样的问题之前,我需要确保我下次查看 API 文档。谢谢你的回答:)。
    • 请注意,这不会显示任何自启动以来没有连接的接口。这意味着如果您有多个接口,例如 eth0eth1,其中只有 eth0 曾经连接过。此方法只会显示eth0 而不会显示eth1
    • 手工创建的虚拟界面会显示出来,例如enp5s0enp5s0:1
    【解决方案2】:

    os.networkInterfaces() 方法返回一个仅包含已分配网络地址的网络接口的对象,但如果我们想要机器中的所有网卡,我们可以使用此方法

    var shell = require('shelljs'); 
    
     var interfaceCard = shell.ls('/sys/class/net');
    

    这个 interfaceCard 有所有网络接口的列表

    输出将是

    [ 'eth0',
    'eth1',
    'lo',
     stdout: 'eth0\neth1\nlo\n',
      stderr: null,
    code: 0,
    cat: [Function: bound ],
    exec: [Function: bound ],
    grep: [Function: bound ],
    head: [Function: bound ],
     sed: [Function: bound ],
    sort: [Function: bound ],
     tail: [Function: bound ],
      to: [Function: bound ],
     toEnd: [Function: bound ],
     uniq: [Function: bound ] ]
    
     interfaceCard=interfaceCard.stdout.split('\n');
    
     interfaceCard = eth0, eth1, lo
    

    【讨论】:

      【解决方案3】:

      如果您只想列出接口的名称:

       Object.keys(os.getNetworkInterfaces())
        // [ 'lo0', 'en0', 'en3', 'awdl0' ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多