如何使用NodeJs获取网络接口的网关地址?
获取网络接口的网关地址解决方案
Node.js 的 os.networkInterfaces() API 本身不会返回网关信息,要获取网关得通过执行对应平台的系统命令,解析输出结果来实现。下面是跨平台的实现方案:
实现思路
- Windows:执行
route print命令,解析默认路由的网关地址 - macOS/Linux:执行
netstat -rn(兼容更多系统),提取对应接口的默认路由网关
完整代码
const os = require('os'); const { execSync } = require('child_process'); // 解析指定接口的网关地址 const getGateway = (interfaceName) => { let gateway = 'Unknown'; const platform = os.platform(); try { let output; if (platform === 'win32') { // Windows 平台过滤默认路由条目 output = execSync('route print 0.0.0.0', { encoding: 'utf8' }); const gatewayMatch = output.match(/0\.0\.0\.0\s+0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/); if (gatewayMatch) gateway = gatewayMatch[1]; } else if (platform === 'darwin' || platform === 'linux') { // macOS/Linux 平台解析路由表 output = execSync('netstat -rn', { encoding: 'utf8' }); const lines = output.split('\n'); for (const line of lines) { const parts = line.trim().split(/\s+/); // 匹配默认路由条目 if (parts[0] === '0.0.0.0' || parts[0] === 'default') { // 匹配目标接口(macOS 是最后一列,Linux 是倒数第二列) const iface = platform === 'darwin' ? parts.at(-1) : parts.at(-2); if (iface === interfaceName) { gateway = parts[1]; break; } } } } } catch (err) { console.error('获取网关失败:', err.message); } return gateway; }; const getNetInfo = () => { let networkInterfaces = os.networkInterfaces(); let nets = []; Object.keys(networkInterfaces).forEach(name => { networkInterfaces[name]?.forEach(n => { if (n.family === "IPv4" && !n.internal) { const gateway = getGateway(name); nets.push({ interface: name, gateway: gateway, ...n }); } }); }); return nets; }; // 测试调用示例 console.log(JSON.stringify(getNetInfo(), null, 2));
关键说明
- 使用
execSync同步执行系统命令,适合简单场景;如果是异步业务场景,可以替换为exec或spawn - 不同平台的命令输出格式存在差异,需针对性解析:
- Windows 下通过
route print 0.0.0.0过滤出默认路由,直接匹配网关 IP - macOS/Linux 下通过
netstat -rn输出的路由表,匹配对应接口的默认路由条目提取网关
- Windows 下通过
- 加入异常捕获逻辑,避免命令执行失败导致整个函数崩溃
内容的提问来源于stack exchange,提问作者Mendes
相关产品推荐
相关产品推荐

