开发者

Retrieving a List of network interfaces in node.js (ioctl SIOCGIFCONF)

开发者 https://www.devze.com 2023-04-13 09:26 出处:网络
I\'m new to node and am hacking together a node application utilizing node_pcap to capture packet data and do interesting things with it.One of the inputs to capturing data is the network interface to

I'm new to node and am hacking together a node application utilizing node_pcap to capture packet data and do interesting things with it. One of the inputs to capturing data is the network interface to listen on, i.e. "eth0".

I thought it would be really great if I could programmatically look up the available interfaces on the system and present them to the user of the program and allow them to pick which interface to listen on. In C, I would use ioctl (or ioctlsocket with winsock) using SIOCGIFCONF.

My question is, does there currently exist a mechanism to do this in node? I've s开发者_C百科earched quite a bit and haven't arrived to any such solution.

If this functionality does not currently exist, I would assume I'd be able to write a Module binding in C/C++ using ioctl to accomplish this.

Thank you for your time!


Update valid as of Node 13.7.0

This has been renamed since this answer was submitted. It is now just networkInterfaces() like this:

require('os').networkInterfaces()

Or probably preferably like this:

import { networkInterfaces } from 'os';

const interfaces = networkInterfaces();

New docs url: https://nodejs.org/docs/latest/api/os.html#os_os_networkinterfaces

Original answer

As of Node.js 0.6.0 you have

require('os').getNetworkInterfaces()

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


If you want to list only the name of interfaces :

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


os.networkInterfaces() method returns an object containing only network interfaces that have been assigned a network addresS but if we want all network card in machine we can use this method

var shell = require('shelljs'); 

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

this interfaceCard has list of all network interfaces

output will be

[ '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
0

精彩评论

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