我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
调用ifconfig是非常依赖于平台的,而且网络层知道套接字所在的IP地址,所以最好是询问它。
Node.js并没有公开这样做的直接方法,但是你可以打开任何套接字,并询问正在使用的本地IP地址。例如,打开www.google.com的套接字:
var net = require('net');
function getNetworkIP(callback) {
var socket = net.createConnection(80, 'www.google.com');
socket.on('connect', function() {
callback(undefined, socket.address().address);
socket.end();
});
socket.on('error', function(e) {
callback(e, 'error');
});
}
使用情况:
getNetworkIP(function (error, ip) {
console.log(ip);
if (error) {
console.log('error:', error);
}
});
其他回答
谷歌在搜索“Node.js获取服务器IP”时引导我到这个问题,所以让我们为那些试图在他们的Node.js服务器程序中实现这一点的人提供一个替代答案(可能是原始海报的情况)。
在最简单的情况下,服务器只绑定到一个IP地址,应该不需要确定IP地址,因为我们已经知道将它绑定到哪个地址(例如,传递给listen()函数的第二个参数)。
在不太简单的情况下,服务器绑定到多个IP地址,我们可能需要确定客户端连接到的接口的IP地址。正如Tor Valamo所简单建议的,现在,我们可以很容易地从连接的套接字及其localAddress属性中获得这些信息。
例如,如果程序是web服务器:
var http = require("http")
http.createServer(function (req, res) {
console.log(req.socket.localAddress)
res.end(req.socket.localAddress)
}).listen(8000)
如果它是一个通用TCP服务器:
var net = require("net")
net.createServer(function (socket) {
console.log(socket.localAddress)
socket.end(socket.localAddress)
}).listen(8000)
在运行服务器程序时,该解决方案提供了非常高的可移植性、准确性和效率。
详情请参见:
http://nodejs.org/api/net.html http://nodejs.org/api/http.html
对上面答案的改进,原因如下:
Code should be as self-explanatory as possible. Enumerating over an array using for...in... should be avoided. for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available. var os = require('os'), interfaces = os.networkInterfaces(), address, addresses = [], i, l, interfaceId, interfaceArray; for (interfaceId in interfaces) { if (interfaces.hasOwnProperty(interfaceId)) { interfaceArray = interfaces[interfaceId]; l = interfaceArray.length; for (i = 0; i < l; i += 1) { address = interfaceArray[i]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } } console.log(addresses);
公认的答案是异步的。我想要一个同步版本:
var os = require('os');
var ifaces = os.networkInterfaces();
console.log(JSON.stringify(ifaces, null, 4));
for (var iface in ifaces) {
var iface = ifaces[iface];
for (var alias in iface) {
var alias = iface[alias];
console.log(JSON.stringify(alias, null, 4));
if ('IPv4' !== alias.family || alias.internal !== false) {
debug("skip over internal (i.e. 127.0.0.1) and non-IPv4 addresses");
continue;
}
console.log("Found IP address: " + alias.address);
return alias.address;
}
}
return false;
更大的问题是“为什么?”
如果你需要知道Node.js实例监听的服务器,你可以使用req.hostname。
这些信息可以在os.networkInterfaces()中找到,这是一个对象,它将网络接口名称映射到它的属性(例如,一个接口可以有几个地址):
'use strict';
const { networkInterfaces } = require('os');
const nets = networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
// 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
const familyV4Value = typeof net.family === 'string' ? 'IPv4' : 4
if (net.family === familyV4Value && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
// 'results'
{
"en0": [
"192.168.1.101"
],
"eth0": [
"10.0.0.101"
],
"<network name>": [
"<ip>",
"<ip alias>",
"<ip alias>",
...
]
}
// results["en0"][0]
"192.168.1.101"