在 Node.js 中获取本地 IP 地址

发布于 2024-09-18 02:15:33 字数 74 浏览 2 评论 0原文

我的机器上运行着一个简单的 Node.js 程序,我想获取运行我的程序的 PC 的本地 IP 地址。如何使用 Node.js 获取它?

I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

陪你搞怪i 2024-09-25 02:15:35

使用:

var os = require('os');
var networkInterfaces = os.networkInterfaces();
var arr = networkInterfaces['Local Area Connection 3']
var ip = arr[1].address;

Use:

var os = require('os');
var networkInterfaces = os.networkInterfaces();
var arr = networkInterfaces['Local Area Connection 3']
var ip = arr[1].address;
探春 2024-09-25 02:15:34

我只使用 Node.js 就能做到这一点。

作为 Node.js:

var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
    .reduce((r,a) => {
        r = r.concat(a)
        return r;
    }, [])
    .filter(({family, address}) => {
        return family.toLowerCase().indexOf('v4') >= 0 &&
            address !== '127.0.0.1'
    })
    .map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);

作为 Bash 脚本(需要安装 Node.js)

function ifconfig2 ()
{
    node -e """
        var os = require( 'os' );
        var networkInterfaces = Object.values(os.networkInterfaces())
            .reduce((r,a)=>{
                r = r.concat(a)
                return r;
            }, [])
            .filter(({family, address}) => {
                return family.toLowerCase().indexOf('v4') >= 0 &&
                    address !== '127.0.0.1'
            })
            .map(({address}) => address);
        var ipAddresses = networkInterfaces.join(', ')
        console.log(ipAddresses);
    """
}

I was able to do this using just Node.js.

As Node.js:

var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
    .reduce((r,a) => {
        r = r.concat(a)
        return r;
    }, [])
    .filter(({family, address}) => {
        return family.toLowerCase().indexOf('v4') >= 0 &&
            address !== '127.0.0.1'
    })
    .map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);

As Bash script (needs Node.js installed)

function ifconfig2 ()
{
    node -e """
        var os = require( 'os' );
        var networkInterfaces = Object.values(os.networkInterfaces())
            .reduce((r,a)=>{
                r = r.concat(a)
                return r;
            }, [])
            .filter(({family, address}) => {
                return family.toLowerCase().indexOf('v4') >= 0 &&
                    address !== '127.0.0.1'
            })
            .map(({address}) => address);
        var ipAddresses = networkInterfaces.join(', ')
        console.log(ipAddresses);
    """
}
涙—继续流 2024-09-25 02:15:34

我编写了一个 Node.js 模块,它通过查看哪个来确定您的本地 IP 地址网络接口包含您的默认网关。

这比从 os.networkInterfaces() 中选择接口或主机名的 DNS 查找更可靠。它能够忽略 VMware 虚拟接口、环回和 VPN 接口,并且可以在 Windows、Linux、Mac OS 和 FreeBSD 上运行。在底层,它执行 route.exenetstat 并解析输出。

var localIpV4Address = require("local-ipv4-address");

localIpV4Address().then(function(ipAddress){
    console.log("My IP address is " + ipAddress);
    // My IP address is 10.4.4.137 
});

I wrote a Node.js module that determines your local IP address by looking at which network interface contains your default gateway.

This is more reliable than picking an interface from os.networkInterfaces() or DNS lookups of the hostname. It is able to ignore VMware virtual interfaces, loopback, and VPN interfaces, and it works on Windows, Linux, Mac OS, and FreeBSD. Under the hood, it executes route.exe or netstat and parses the output.

var localIpV4Address = require("local-ipv4-address");

localIpV4Address().then(function(ipAddress){
    console.log("My IP address is " + ipAddress);
    // My IP address is 10.4.4.137 
});
Smile简单爱 2024-09-25 02:15:34

对于 Linux 和 macOS 使用,如果您想通过同步方式获取 IP 地址,请尝试以下操作:

var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);

结果将如下所示:

['192.168.3.2', '192.168.2.1']

For Linux and macOS uses, if you want to get your IP addresses by a synchronous way, try this:

var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);

The result will be something like this:

['192.168.3.2', '192.168.2.1']
找回味觉 2024-09-25 02:15:34

仅适用于 macOS 第一个本地主机地址的一个衬垫。

在 macOS 上开发应用程序时,您想在手机上测试它,并且需要您的应用程序自动选择本地主机 IP 地址。

require('os').networkInterfaces().en0.find(elm => elm.family=='IPv4').address

这只是提及如何自动查找 IP 地址。
要测试这一点,您可以转到终端点击

node
os.networkInterfaces().en0.find(elm => elm.family=='IPv4').address

输出将是您的本地主机 IP 地址。

One liner for macOS first localhost address only.

When developing applications on macOS, and you want to test it on the phone, and need your app to pick the localhost IP address automatically.

require('os').networkInterfaces().en0.find(elm => elm.family=='IPv4').address

This is just to mention how you can find out the ip address automatically.
To test this you can go to terminal hit

node
os.networkInterfaces().en0.find(elm => elm.family=='IPv4').address

output will be your localhost IP address.

最佳男配角 2024-09-25 02:15:34

对于任何对简洁感兴趣的人,这里有一些不需要不属于标准 Node.js 安装的插件/依赖项的“一行”:

eth0 的公共 IPv4 和 IPv6 地址作为数组:

var ips = require('os').networkInterfaces().eth0.map(function(interface) {
    return interface.address;
});

eth0 的第一个公共 IP 地址(通常是 IPv4)作为字符串:

var ip = require('os').networkInterfaces().eth0[0].address;

For anyone interested in brevity, here are some "one-liners" that do not require plugins/dependencies that aren't part of a standard Node.js installation:

Public IPv4 and IPv6 address of eth0 as an array:

var ips = require('os').networkInterfaces().eth0.map(function(interface) {
    return interface.address;
});

First public IP address of eth0 (usually IPv4) as a string:

var ip = require('os').networkInterfaces().eth0[0].address;
诗笺 2024-09-25 02:15:34

以下解决方案对我有用

const ip = Object.values(require("os").networkInterfaces())
        .flat()
        .filter((item) => !item.internal && item.family === "IPv4")
        .find(Boolean).address;

The following solution works for me

const ip = Object.values(require("os").networkInterfaces())
        .flat()
        .filter((item) => !item.internal && item.family === "IPv4")
        .find(Boolean).address;
怎言笑 2024-09-25 02:15:34

Google 在搜索“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)

当运行服务器程序时,该解决方案提供了非常高的可移植性、准确性和效率。

有关更多详细信息,请参阅:

Google directed me to this question while searching for "Node.js get server IP", so let's give an alternative answer for those who are trying to achieve this in their Node.js server program (may be the case of the original poster).

In the most trivial case where the server is bound to only one IP address, there should be no need to determine the IP address since we already know to which address we bound it (for example, the second parameter passed to the listen() function).

In the less trivial case where the server is bound to multiple IP addresses, we may need to determine the IP address of the interface to which a client connected. And as briefly suggested by Tor Valamo, nowadays, we can easily get this information from the connected socket and its localAddress property.

For example, if the program is a web server:

var http = require("http")

http.createServer(function (req, res) {
    console.log(req.socket.localAddress)
    res.end(req.socket.localAddress)
}).listen(8000)

And if it's a generic TCP server:

var net = require("net")

net.createServer(function (socket) {
    console.log(socket.localAddress)
    socket.end(socket.localAddress)
}).listen(8000)

When running a server program, this solution offers very high portability, accuracy and efficiency.

For more details, see:

倾听心声的旋律 2024-09-25 02:15:34

根据评论,以下是适用于当前版本的 Node.js 的内容:

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

对上述答案之一的评论缺少对 values() 的调用。看起来 os.networkInterfaces() 现在返回一个对象而不是数组。

Based on a comment, here's what's working for the current version of Node.js:

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

The comment on one of the answers above was missing the call to values(). It looks like os.networkInterfaces() now returns an object instead of an array.

妄司 2024-09-25 02:15:34

这是前面示例的变体。它需要小心地过滤掉 VMware 接口等。如果您不传递索引返回所有地址。否则,您可能希望将其默认设置为 0,然后只需传递 null 即可获取所有内容,但您会解决这个问题。如果愿意添加,您还可以为正则表达式过滤器传递另一个参数。

function getAddress(idx) {

    var addresses = [],
        interfaces = os.networkInterfaces(),
        name, ifaces, iface;

    for (name in interfaces) {
        if(interfaces.hasOwnProperty(name)){
            ifaces = interfaces[name];
            if(!/(loopback|vmware|internal)/gi.test(name)){
                for (var i = 0; i < ifaces.length; i++) {
                    iface = ifaces[i];
                    if (iface.family === 'IPv4' &&  !iface.internal && iface.address !== '127.0.0.1') {
                        addresses.push(iface.address);
                    }
                }
            }
        }
    }

    // If an index is passed only return it.
    if(idx >= 0)
        return addresses[idx];
    return addresses;
}

Here is a variation of the previous examples. It takes care to filter out VMware interfaces, etc. If you don't pass an index it returns all addresses. Otherwise, you may want to set it default to 0 and then just pass null to get all, but you'll sort that out. You could also pass in another argument for the regex filter if so inclined to add.

function getAddress(idx) {

    var addresses = [],
        interfaces = os.networkInterfaces(),
        name, ifaces, iface;

    for (name in interfaces) {
        if(interfaces.hasOwnProperty(name)){
            ifaces = interfaces[name];
            if(!/(loopback|vmware|internal)/gi.test(name)){
                for (var i = 0; i < ifaces.length; i++) {
                    iface = ifaces[i];
                    if (iface.family === 'IPv4' &&  !iface.internal && iface.address !== '127.0.0.1') {
                        addresses.push(iface.address);
                    }
                }
            }
        }
    }

    // If an index is passed only return it.
    if(idx >= 0)
        return addresses[idx];
    return addresses;
}
黯淡〆 2024-09-25 02:15:34

如果您喜欢简洁,这里使用 Lodash

var os = require('os');
var _ = require('lodash');
var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address').first();

console.log('First local IPv4 address is ' + firstLocalIp);

If you're into the whole brevity thing, here it is using Lodash:

var os = require('os');
var _ = require('lodash');
var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address').first();

console.log('First local IPv4 address is ' + firstLocalIp);

醉梦枕江山 2024-09-25 02:15:34
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress 
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress 
红尘作伴 2024-09-25 02:15:34

这是我的变体,允许以可移植的方式获取 IPv4 和 IPv6 地址:

/**
 * Collects information about the local IPv4/IPv6 addresses of
 * every network interface on the local computer.
 * Returns an object with the network interface name as the first-level key and
 * "IPv4" or "IPv6" as the second-level key.
 * For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
 * (as string) of eth0
 */
getLocalIPs = function () {
    var addrInfo, ifaceDetails, _len;
    var localIPInfo = {};
    //Get the network interfaces
    var networkInterfaces = require('os').networkInterfaces();
    //Iterate over the network interfaces
    for (var ifaceName in networkInterfaces) {
        ifaceDetails = networkInterfaces[ifaceName];
        //Iterate over all interface details
        for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
            addrInfo = ifaceDetails[_i];
            if (addrInfo.family === 'IPv4') {
                //Extract the IPv4 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv4 = addrInfo.address;
            } else if (addrInfo.family === 'IPv6') {
                //Extract the IPv6 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv6 = addrInfo.address;
            }
        }
    }
    return localIPInfo;
};

这是同一函数的 CoffeeScript 版本:

getLocalIPs = () =>
    ###
    Collects information about the local IPv4/IPv6 addresses of
      every network interface on the local computer.
    Returns an object with the network interface name as the first-level key and
      "IPv4" or "IPv6" as the second-level key.
    For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
      (as string) of eth0
    ###
    networkInterfaces = require('os').networkInterfaces();
    localIPInfo = {}
    for ifaceName, ifaceDetails of networkInterfaces
        for addrInfo in ifaceDetails
            if addrInfo.family=='IPv4'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv4 = addrInfo.address
            else if addrInfo.family=='IPv6'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv6 = addrInfo.address
    return localIPInfo

console.log(getLocalIPs()) 的输出示例

{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
  wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
  tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }

Here's my variant that allows getting both IPv4 and IPv6 addresses in a portable manner:

/**
 * Collects information about the local IPv4/IPv6 addresses of
 * every network interface on the local computer.
 * Returns an object with the network interface name as the first-level key and
 * "IPv4" or "IPv6" as the second-level key.
 * For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
 * (as string) of eth0
 */
getLocalIPs = function () {
    var addrInfo, ifaceDetails, _len;
    var localIPInfo = {};
    //Get the network interfaces
    var networkInterfaces = require('os').networkInterfaces();
    //Iterate over the network interfaces
    for (var ifaceName in networkInterfaces) {
        ifaceDetails = networkInterfaces[ifaceName];
        //Iterate over all interface details
        for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
            addrInfo = ifaceDetails[_i];
            if (addrInfo.family === 'IPv4') {
                //Extract the IPv4 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv4 = addrInfo.address;
            } else if (addrInfo.family === 'IPv6') {
                //Extract the IPv6 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv6 = addrInfo.address;
            }
        }
    }
    return localIPInfo;
};

Here's a CoffeeScript version of the same function:

getLocalIPs = () =>
    ###
    Collects information about the local IPv4/IPv6 addresses of
      every network interface on the local computer.
    Returns an object with the network interface name as the first-level key and
      "IPv4" or "IPv6" as the second-level key.
    For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
      (as string) of eth0
    ###
    networkInterfaces = require('os').networkInterfaces();
    localIPInfo = {}
    for ifaceName, ifaceDetails of networkInterfaces
        for addrInfo in ifaceDetails
            if addrInfo.family=='IPv4'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv4 = addrInfo.address
            else if addrInfo.family=='IPv6'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv6 = addrInfo.address
    return localIPInfo

Example output for console.log(getLocalIPs())

{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
  wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
  tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }
挽容 2024-09-25 02:15:34

与其他答案类似但更简洁:

'use strict';

const interfaces = require('os').networkInterfaces();

const addresses = Object.keys(interfaces)
  .reduce((results, name) => results.concat(interfaces[name]), [])
  .filter((iface) => iface.family === 'IPv4' && !iface.internal)
  .map((iface) => iface.address);

Similar to other answers but more succinct:

'use strict';

const interfaces = require('os').networkInterfaces();

const addresses = Object.keys(interfaces)
  .reduce((results, name) => results.concat(interfaces[name]), [])
  .filter((iface) => iface.family === 'IPv4' && !iface.internal)
  .map((iface) => iface.address);
栖迟 2024-09-25 02:15:34

很多时候,我发现有多个面向内部和外部的接口可用(例如:10.0.75.1172.100.0.1192.168.2.3),我真正想要的是外部的 (172.100.0.1)。

如果其他人有类似的担忧,这里还有一个对此的看法,希望可以有所帮助......

const address = Object.keys(os.networkInterfaces())
    // flatten interfaces to an array
    .reduce((a, key) => [
        ...a,
        ...os.networkInterfaces()[key]
    ], [])
    // non-internal ipv4 addresses only
    .filter(iface => iface.family === 'IPv4' && !iface.internal)
    // project ipv4 address as a 32-bit number (n)
    .map(iface => ({...iface, n: (d => ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]))(iface.address.split('.'))}))
    // set a hi-bit on (n) for reserved addresses so they will sort to the bottom
    .map(iface => iface.address.startsWith('10.') || iface.address.startsWith('192.') ? {...iface, n: Math.pow(2,32) + iface.n} : iface)
    // sort ascending on (n)
    .sort((a, b) => a.n - b.n)
    [0]||{}.address;

Many times I find there are multiple internal and external facing interfaces available (example: 10.0.75.1, 172.100.0.1, 192.168.2.3) , and it's the external one that I'm really after (172.100.0.1).

In case anyone else has a similar concern, here's one more take on this that hopefully may be of some help...

const address = Object.keys(os.networkInterfaces())
    // flatten interfaces to an array
    .reduce((a, key) => [
        ...a,
        ...os.networkInterfaces()[key]
    ], [])
    // non-internal ipv4 addresses only
    .filter(iface => iface.family === 'IPv4' && !iface.internal)
    // project ipv4 address as a 32-bit number (n)
    .map(iface => ({...iface, n: (d => ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]))(iface.address.split('.'))}))
    // set a hi-bit on (n) for reserved addresses so they will sort to the bottom
    .map(iface => iface.address.startsWith('10.') || iface.address.startsWith('192.') ? {...iface, n: Math.pow(2,32) + iface.n} : iface)
    // sort ascending on (n)
    .sort((a, b) => a.n - b.n)
    [0]||{}.address;
梦归所梦 2024-09-25 02:15:33

此信息可以在 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"

This information can be found in os.networkInterfaces(), — an object, that maps network interface names to its properties (so that one interface can, for example, have several addresses):

'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"
场罚期间 2024-09-25 02:15:33

这是我用的。

const dns = require('node:dns');
const os = require('node:os');

const options = { family: 4 };

dns.lookup(os.hostname(), options, (err, addr) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`IPv4 address: ${addr}`);
  }
});

这将返回您的第一个网络接口的 IPv4 地址。它也可能有 IPv6,因此为了获取“首先列出的内容”,您可以使用 family:0 (或根本不传递任何选项)或显式获取 IPv6,使用family:6 作为选项。

Here's what I use.

const dns = require('node:dns');
const os = require('node:os');

const options = { family: 4 };

dns.lookup(os.hostname(), options, (err, addr) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`IPv4 address: ${addr}`);
  }
});

This will return your first network interface's IPv4 address. It might also have an IPv6, so in order to get "whatever is listed first" you can use family:0 (or don't pass any options at all) or to explicitly get the IPv6, use family:6 as option instead.

掩于岁月 2024-09-25 02:15:33

https://github.com/indutny/node-ip

var ip = require("ip");
console.dir ( ip.address() );

https://github.com/indutny/node-ip

var ip = require("ip");
console.dir ( ip.address() );
九局 2024-09-25 02:15:33

您可以使用 os 模块找到您计算机的任何 IP 地址 - 这是 Node.js 本机

var os = require('os');

var networkInterfaces = os.networkInterfaces();

console.log(networkInterfaces);

您所需要做的就是调用 os.networkInterfaces(),您将获得一个易于管理的列表 - 比运行更容易ifconfig 按联赛。

Any IP address of your machine you can find by using the os module - and that's native to Node.js:

var os = require('os');

var networkInterfaces = os.networkInterfaces();

console.log(networkInterfaces);

All you need to do is call os.networkInterfaces() and you'll get an easy manageable list - easier than running ifconfig by leagues.

一腔孤↑勇 2024-09-25 02:15:33

这是我获取本地 IP 地址的实用方法,假设您正在寻找 IPv4 地址并且机器只有一个真实的网络接口。它可以轻松地重构以返回多接口计算机的 IP 地址数组。

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }
  return '0.0.0.0';
}

Here's my utility method for getting the local IP address, assuming you are looking for an IPv4 address and the machine only has one real network interface. It could easily be refactored to return an array of IP addresses for multi-interface machines.

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }
  return '0.0.0.0';
}
人间☆小暴躁 2024-09-25 02:15:33

安装一个名为 ip 的模块,例如:

npm install ip

然后使用以下代码:

var ip = require("ip");
console.log(ip.address());

Install a module called ip like:

npm install ip

Then use this code:

var ip = require("ip");
console.log(ip.address());
锦上情书 2024-09-25 02:15:33

使用 npm ip 模块:

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'

Use the npm ip module:

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'
醉态萌生 2024-09-25 02:15:33

以下是 Node.js 代码片段,它将解析 ifconfig 的输出并(异步)返回找到的第一个 IP 地址:(

已在 Mac OS X v10.6(仅限 Snow Leopard);我希望它也适用于 Linux。)

var getNetworkIP = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
        // TODO: implement for OSes without the ifconfig command
        case 'darwin':
             command = 'ifconfig';
             filterRE = /\binet\s+([^\s]+)/g;
             // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
             break;
        default:
             command = 'ifconfig';
             filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
             // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
             break;
    }

    return function (callback, bypassCache) {
        // Get cached value
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }

        // System call
        exec(command, function (error, stdout, sterr) {
            var ips = [];
            // Extract IP addresses
            var matches = stdout.match(filterRE);

            // JavaScript doesn't have any lookbehind regular expressions, so we need a trick
            for (var i = 0; i < matches.length; i++) {
                ips.push(matches[i].replace(filterRE, '$1'));
            }

            // Filter BS
            for (var i = 0, l = ips.length; i < l; i++) {
                if (!ignoreRE.test(ips[i])) {
                    //if (!error) {
                        cached = ips[i];
                    //}
                    callback(error, ips[i]);
                    return;
                }
            }
            // Nothing found
            callback(error, null);
        });
    };
})();

用法示例:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
}, false);

如果第二个参数为true,函数每次都会执行一次系统调用;否则使用缓存的值。


更新版本

返回所有本地网络地址的数组。

Ubuntu 11.04 (Natty Narwhal) 和 Windows XP 32 上测试

var getNetworkIPs = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
        case 'win32':
        //case 'win64': // TODO: test
            command = 'ipconfig';
            filterRE = /\bIPv[46][^:\r\n]+:\s*([^\s]+)/g;
            break;
        case 'darwin':
            command = 'ifconfig';
            filterRE = /\binet\s+([^\s]+)/g;
            // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
            break;
        default:
            command = 'ifconfig';
            filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
            // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
            break;
    }

    return function (callback, bypassCache) {
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }

        // System call
        exec(command, function (error, stdout, sterr) {
            cached = [];
            var ip;
            var matches = stdout.match(filterRE) || [];
            //if (!error) {
            for (var i = 0; i < matches.length; i++) {
                ip = matches[i].replace(filterRE, '$1')
                if (!ignoreRE.test(ip)) {
                    cached.push(ip);
                }
            }
            //}
            callback(error, cached);
        });
    };
})();

更新版本的使用示例

getNetworkIPs(function (error, ip) {
console.log(ip);
if (error) {
    console.log('error:', error);
}
}, false);

Here is a snippet of Node.js code that will parse the output of ifconfig and (asynchronously) return the first IP address found:

(It was tested on Mac OS X v10.6 (Snow Leopard) only; I hope it works on Linux too.)

var getNetworkIP = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
        // TODO: implement for OSes without the ifconfig command
        case 'darwin':
             command = 'ifconfig';
             filterRE = /\binet\s+([^\s]+)/g;
             // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
             break;
        default:
             command = 'ifconfig';
             filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
             // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
             break;
    }

    return function (callback, bypassCache) {
        // Get cached value
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }

        // System call
        exec(command, function (error, stdout, sterr) {
            var ips = [];
            // Extract IP addresses
            var matches = stdout.match(filterRE);

            // JavaScript doesn't have any lookbehind regular expressions, so we need a trick
            for (var i = 0; i < matches.length; i++) {
                ips.push(matches[i].replace(filterRE, '$1'));
            }

            // Filter BS
            for (var i = 0, l = ips.length; i < l; i++) {
                if (!ignoreRE.test(ips[i])) {
                    //if (!error) {
                        cached = ips[i];
                    //}
                    callback(error, ips[i]);
                    return;
                }
            }
            // Nothing found
            callback(error, null);
        });
    };
})();

Usage example:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
}, false);

If the second parameter is true, the function will execute a system call every time; otherwise the cached value is used.


Updated version

Returns an array of all local network addresses.

Tested on Ubuntu 11.04 (Natty Narwhal) and Windows XP 32

var getNetworkIPs = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
        case 'win32':
        //case 'win64': // TODO: test
            command = 'ipconfig';
            filterRE = /\bIPv[46][^:\r\n]+:\s*([^\s]+)/g;
            break;
        case 'darwin':
            command = 'ifconfig';
            filterRE = /\binet\s+([^\s]+)/g;
            // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
            break;
        default:
            command = 'ifconfig';
            filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
            // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
            break;
    }

    return function (callback, bypassCache) {
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }

        // System call
        exec(command, function (error, stdout, sterr) {
            cached = [];
            var ip;
            var matches = stdout.match(filterRE) || [];
            //if (!error) {
            for (var i = 0; i < matches.length; i++) {
                ip = matches[i].replace(filterRE, '$1')
                if (!ignoreRE.test(ip)) {
                    cached.push(ip);
                }
            }
            //}
            callback(error, cached);
        });
    };
})();

Usage Example for updated version

getNetworkIPs(function (error, ip) {
console.log(ip);
if (error) {
    console.log('error:', error);
}
}, false);
云柯 2024-09-25 02:15:33

调用 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);
    }
});

Calling ifconfig is very platform-dependent, and the networking layer does know what IP addresses a socket is on, so best is to ask it.

Node.js doesn't expose a direct method of doing this, but you can open any socket, and ask what local IP address is in use. For example, opening a socket to 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');
  });
}

Usage case:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
});
余生共白头 2024-09-25 02:15:33

您的本地 IP 地址始终为 127.0.0.1。

然后是网络 IP 地址,您可以从 ifconfig (*nix) 或 ipconfig (win) 获取该地址。这仅在本地网络内有用。

然后是外部/公共 IP 地址,只有当您可以以某种方式向路由器询问该地址时,您才能获得该地址,或者您可以设置一个外部服务,该服务在收到请求时返回客户端 IP 地址。还有其他此类服务,例如whatismyip.com。

在某些情况下(例如,如果您有 WAN 连接),网络 IP 地址和公共 IP 是相同的,并且都可以在外部使用来访问您的计算机。

如果您的网络和公共 IP 地址不同,您可能需要让网络路由器将所有传入连接转发到您的网络 IP 地址。


2013 年更新:

现在有一种新方法可以做到这一点。您可以检查连接的套接字对象是否有名为localAddress 的属性,例如net.socket.localAddress。它返回套接字一端的地址。

最简单的方法是打开一个随机端口并侦听它,然后获取您的地址并关闭套接字。


2015 年更新:

以前的已经不行了。

Your local IP address is always 127.0.0.1.

Then there is the network IP address, which you can get from ifconfig (*nix) or ipconfig (win). This is only useful within the local network.

Then there is your external/public IP address, which you can only get if you can somehow ask the router for it, or you can setup an external service which returns the client IP address whenever it gets a request. There are also other such services in existence, like whatismyip.com.

In some cases (for instance if you have a WAN connection) the network IP address and the public IP are the same, and can both be used externally to reach your computer.

If your network and public IP addresses are different, you may need to have your network router forward all incoming connections to your network IP address.


Update 2013:

There's a new way of doing this now. You can check the socket object of your connection for a property called localAddress, e.g. net.socket.localAddress. It returns the address on your end of the socket.

The easiest way is to just open a random port and listen on it, and then get your address and close the socket.


Update 2015:

The previous doesn't work anymore.

小兔几 2024-09-25 02:15:33

我可能来晚了这个问题,但万一有人想要一个单行 ES6 解决方案来获取 IP 地址数组,那么这应该对你有帮助:

Object.values(require("os").networkInterfaces())
    .flat()
    .filter(({ family, internal }) => family === "IPv4" && !internal)
    .map(({ address }) => address)

因为

Object.values(require("os").networkInterfaces())

将返回一个数组数组,所以 flat() 用于将其展平为单个数组

.filter(({ family, internal }) => family === "IPv4" && !internal)

将过滤数组以仅包含 IPv4 地址,如果它不是内部的

最后

.map(({ address }) => address)

将仅返回过滤数组的 IPv4 地址,

因此结果将是 [ '192.168.xx.xx ' ]

如果您想要或更改过滤条件,则可以获取该数组的第一个索引

OS 使用的是 Windows

I probably came late to this question, but in case someone wants to a get a one liner ES6 solution to get array of IP addresses then this should help you:

Object.values(require("os").networkInterfaces())
    .flat()
    .filter(({ family, internal }) => family === "IPv4" && !internal)
    .map(({ address }) => address)

As

Object.values(require("os").networkInterfaces())

will return an array of arrays, so flat() is used to flatten it into a single array

.filter(({ family, internal }) => family === "IPv4" && !internal)

Will filter the array to include only IPv4 Addresses and if it's not internal

Finally

.map(({ address }) => address)

Will return only the IPv4 address of the filtered array

so result would be [ '192.168.xx.xx' ]

you can then get the first index of that array if you want or change filter condition

OS used is Windows

空宴 2024-09-25 02:15:33

Underscore.jsLodash 是:

var ip = require('underscore')
    .chain(require('os').networkInterfaces())
    .values()
    .flatten()
    .find({family: 'IPv4', internal: false})
    .value()
    .address;

The correct one-liner for both Underscore.js and Lodash is:

var ip = require('underscore')
    .chain(require('os').networkInterfaces())
    .values()
    .flatten()
    .find({family: 'IPv4', internal: false})
    .value()
    .address;
骄兵必败 2024-09-25 02:15:33

这可能是最干净、最简单的答案,没有依赖和依赖。适用于所有平台。

const { lookup } = require('dns').promises;
const { hostname } = require('os');

async function getMyIPAddress(options) {
  return (await lookup(hostname(), options))
    .address;
}

Here's what might be the cleanest, simplest answer without dependencies & that works across all platforms.

const { lookup } = require('dns').promises;
const { hostname } = require('os');

async function getMyIPAddress(options) {
  return (await lookup(hostname(), options))
    .address;
}
涫野音 2024-09-25 02:15:33

我所知道的是我想要以 192.168. 开头的 IP 地址。这段代码将为您提供:

function getLocalIp() {
    const os = require('os');

    for(let addresses of Object.values(os.networkInterfaces())) {
        for(let add of addresses) {
            if(add.address.startsWith('192.168.')) {
                return add.address;
            }
        }
    }
}

当然,如果您正在寻找不同的数字,您可以只更改数字。

All I know is I wanted the IP address beginning with 192.168.. This code will give you that:

function getLocalIp() {
    const os = require('os');

    for(let addresses of Object.values(os.networkInterfaces())) {
        for(let add of addresses) {
            if(add.address.startsWith('192.168.')) {
                return add.address;
            }
        }
    }
}

Of course you can just change the numbers if you're looking for a different one.

奢华的一滴泪 2024-09-25 02:15:33

这是一个用普通 JavaScript 编写的简化版本,用于获取单个 IP 地址:

function getServerIp() {

  const os = require('os');
  const ifaces = os.networkInterfaces();
  let values = Object.keys(ifaces).map(function(name) {
    return ifaces[name];
  });
  values = [].concat.apply([], values).filter(function(val){
    return val.family == 'IPv4' && val.internal == false;
  });

  return values.length ? values[0].address : '0.0.0.0';
}

Here's a simplified version in vanilla JavaScript to obtain a single IP address:

function getServerIp() {

  const os = require('os');
  const ifaces = os.networkInterfaces();
  let values = Object.keys(ifaces).map(function(name) {
    return ifaces[name];
  });
  values = [].concat.apply([], values).filter(function(val){
    return val.family == 'IPv4' && val.internal == false;
  });

  return values.length ? values[0].address : '0.0.0.0';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文