Nodejs: how to get local IP address in node

Nodejs: how to get local IP address in node

function getIPAdress(){ 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; } } } }


6 回复

Node.js: How to Get Local IP Address

In Node.js, you can easily retrieve the local IP address of your machine by utilizing the os module. This module provides a variety of operating system-related utility functions, including information about network interfaces.

Here’s a function that will return the first non-internal IPv4 address found on any of your network interfaces:

function getLocalIPAddress() {
    const os = require('os');
    const interfaces = os.networkInterfaces();

    for (const devName in interfaces) {
        const iface = interfaces[devName];

        for (const alias of iface) {
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }

    // If no valid IP address is found, return null or an error message.
    return null;
}

// Example usage:
const ipAddress = getLocalIPAddress();
console.log(`Local IP Address: ${ipAddress}`);

Explanation

  1. Importing the os Module:

    • The os module is required at the beginning of the script using require('os'). This module provides basic operating system-related information and utilities.
  2. Accessing Network Interfaces:

    • The os.networkInterfaces() method returns an object containing the network interfaces of the machine. Each key in this object represents a network interface name, and the value is an array of objects representing each interface configuration.
  3. Iterating Through Interfaces:

    • We loop through each network interface using a for...in loop.
    • For each interface, we iterate through its configuration objects using another loop.
  4. Filtering Valid IP Addresses:

    • Inside the inner loop, we check if the current configuration (alias) is an IPv4 address (alias.family === 'IPv4'), not the loopback address (alias.address !== '127.0.0.1'), and not an internal address (!alias.internal).
    • If all conditions are met, we return the IP address.
  5. Returning Default Value:

    • If no valid IP address is found after iterating through all interfaces, the function returns null.

Usage Example

To use the function, simply call it and log the result:

const ipAddress = getLocalIPAddress();
if (ipAddress) {
    console.log(`Local IP Address: ${ipAddress}`);
} else {
    console.log("No valid IP address found.");
}

This function should work well for most cases where you need to find the local IP address of the machine running your Node.js application.


http://blog.csdn.net/marujunyy/article/details/8487267

这篇里面提供了获取本地外网ip的方法,有点yd

在 Node.js 中获取本地 IP 地址可以通过 os 模块中的 networkInterfaces 方法来实现。以下是一个示例代码,可以获取第一个非内部 IPv4 地址。

const os = require('os');

function getIPAddress() {
    const interfaces = os.networkInterfaces();

    for (const devName in interfaces) {
        const iface = interfaces[devName];

        for (const alias of iface) {
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }

    return 'No IP found';
}

console.log(getIPAddress());

解释

  1. 引入模块:使用 require('os') 引入 os 模块。
  2. 定义函数:定义一个名为 getIPAddress 的函数。
  3. 获取网络接口:使用 os.networkInterfaces() 获取所有网络接口信息。
  4. 遍历网络接口:通过 for...in 循环遍历每个网络接口。
  5. 检查每个地址:对于每个接口的地址,检查其类型是否为 IPv4,是否是回环地址 (127.0.0.1) 和是否为内部地址。
  6. 返回结果:如果找到符合条件的地址,则返回该地址;否则返回默认值(如 No IP found)。

这个函数会返回第一个满足条件的非内部 IPv4 地址。如果你需要获取所有满足条件的 IP 地址,可以在函数中进行相应的修改。

回到顶部