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

时间:2022-02-25 23:32:39

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

我有一个简单的节点。在我的机器上运行的js程序,我想获得我的程序运行的PC的本地IP地址。如何用node.js获得它?

34 个解决方案

#1


286  

'use strict';

var os = require('os');
var ifaces = os.networkInterfaces();

Object.keys(ifaces).forEach(function (ifname) {
  var alias = 0;

  ifaces[ifname].forEach(function (iface) {
    if ('IPv4' !== iface.family || iface.internal !== false) {
      // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
      return;
    }

    if (alias >= 1) {
      // this single interface has multiple ipv4 addresses
      console.log(ifname + ':' + alias, iface.address);
    } else {
      // this interface has only one ipv4 adress
      console.log(ifname, iface.address);
    }
    ++alias;
  });
});

// en0 192.168.1.101
// eth0 10.0.0.101

#2


196  

os.networkInterfaces as of right now doesn't work on windows. Running programs to parse the results seems a bit iffy. Here's what I use.

net接口目前还不能在windows上工作。运行程序来解析结果似乎有点不可靠。以下是我使用。

require('dns').lookup(require('os').hostname(), function (err, add, fam) {
  console.log('addr: '+add);
})

This should return your first network interface local ip.

这将返回您的第一个网络接口本地ip。

#3


100  

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

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

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

#4


37  

Any IP of your machine you can find by using the os module - and that's native to NodeJS

您可以通过使用os模块找到您的机器的任何IP——这是NodeJS的本地代码。

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

只需调用os. networkinterface(),就会得到一个易于管理的列表——比按联盟运行ifconfig要容易

http://nodejs.org/api/os.html#os_os_networkinterfaces

http://nodejs.org/api/os.html os_os_networkinterfaces

Best

最好的

Edoardo

Edoardo

#5


30  

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

这是节点的一个片段。用于解析ifconfig的输出并(异步地)返回发现的第一个IP地址的js代码:

(tested on MacOS Snow Leopard only; hope it works on linux too)

(只在MacOS雪豹上测试;希望它也适用于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 OSs without 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 IPs
            var matches = stdout.match(filterRE);
            // JS has no lookbehind REs, 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 exec a system call every time; otherwise the cached value is used.

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


Updated version

Returns an array of all local network addresses.

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

Tested on Ubuntu 11.04 and Windows XP 32

在Ubuntu 11.04和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);

#6


22  

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 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:

调用ifconfig是非常依赖于平台的,网络层确实知道套接字的ip地址,所以最好是问它。Node不会公开直接的方法,但是您可以打开任何套接字,并询问正在使用的本地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');
  });
}

Usage case:

使用情况:

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

#7


22  

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 IPs for multi-interface machines.

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

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';
}

#8


18  

Your local IP is always 127.0.0.1.

您的本地IP总是127.0.0.1。

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

然后是网络IP,可以从ifconfig (*nix)或ipconfig (win)获得。这只在本地网络中有用。

Then there is your external/public IP, 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.

然后是您的外部/公共IP,您只能通过某种方式向路由器请求它,或者您可以设置一个外部服务,该服务在收到请求时返回客户端IP地址。还有其他类似的服务,比如whatismyip.com。

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

在某些情况下(例如,如果您有一个广域网路连接),网络IP和公共IP是相同的,并且两者都可以用于外部以到达您的计算机。

If your network and public IPs are different, you may need to have your network router forward all incoming connections to your network ip.

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


Update 2013:

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.

现在有了一种新的方法,您可以检查连接的socket对象以获得一个名为localAddress的属性,例如net. socket.com .localAddress。它将返回套接字末尾的地址。

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

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


Update 2015:

2015年更新:

The previous doesn't work anymore.

前一个不再起作用了。

#9


15  

Install a module called ip like

安装一个名为ip like的模块

npm install ip

then use this code.

然后使用这段代码。

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

#10


8  

The correct one liner for both underscore and lodash is:

对于下划线和lodash,正确的一行是:

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

#11


8  

use npm ip module

使用npm ip模块

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'

#12


5  

Here's a simplified version in vanilla javascript to obtain a single ip:

这里有一个简化版本的香草javascript获得一个单一的ip:

function getServerIp() {

  var os = require('os');
  var ifaces = os.networkInterfaces();
  var 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';
}

#13


4  

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

对于任何对简洁感兴趣的人,以下是一些不需要插件/依赖的“一行程序”,它们不是标准节点安装的一部分:

Public IPv4 and IPv6 of eth0 as an Array:

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

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

First Public IP of eth0 (usually IPv4) as String:

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

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

#14


4  

for Linux and MacOS uses, if you want to get your IPs by a synchronous way, try this.

对于Linux和MacOS,如果您想通过同步方式获取IPs,可以尝试一下。

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' ]

#15


3  

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

基于上面的评论,以下是当前版本的Node:

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.

上面一个答案的注释忽略了对values()的调用。看起来os.networkInterfaces()现在返回一个对象,而不是数组。

#16


3  

Here is a variation of the above 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 then just pass null to get all, but you'll sort that out. You could also pass in another arg for the regex filter if so inclined to add

这里是上述例子的一个变体。它会过滤vMware接口等等。如果你不传递一个索引,它会返回所有地址,否则你可能想把它设为默认值为0,然后传递null来获取所有地址,但是你会把它分类。如果想要添加regex过滤器,也可以传递另一个arg。

    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;
}

#17


3  

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

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

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.

这比从os.networkInterfaces()或DNS主机名查找中选择接口更可靠。它可以忽略VMware虚拟接口、环回和VPN接口,并且可以在Windows、Linux、Mac OS和FreeBSD上运行。在引擎盖下面,它执行路线。exe或netstat并解析输出。

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

#18


2  

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).

谷歌在搜索“node”时将我引向了这个问题。js获取服务器ip”,所以让我们为那些试图在其节点中实现这一点的人提供一个替代答案。js服务器程序(可能是原始海报的情况)。

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 (eg. second parameter passed to the listen() function).

在服务器只绑定一个IP地址的最普通的情况下,不需要确定IP地址,因为我们已经知道将它绑定到哪个地址(例如)。传递给listen()函数的第二个参数。

In the less trivial case where the server is bound to multiple IPs 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.

在服务器绑定到多个IP地址的情况下,我们可能需要确定客户端连接的接口的IP地址。正如Tor Valamo所建议的,现在我们可以很容易地从连接的套接字和它的localAddress属性中获取这些信息。

For example, if the program is a web server:

例如,如果程序是web服务器:

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:

如果是通用的TCP服务器:

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:

更多细节,请参阅:

#19


2  

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);

#20


1  

Here is a multi-ip version of jhurliman's answer above:

以下是jhurliman的多重ip回答:

function getIPAddresses() {

    var ipAddresses = [];

    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) {
                ipAddresses.push(alias.address);
            }
        }
    }

    return ipAddresses;
}

#21


1  

I realise this is an old thread, but I'd like to offer an improvement on the top answer for the following reasons:

我意识到这是一个老问题,但我想在上面给出一个改进的答案,理由如下:

  • Code should be as self explanatory as possible.
  • 代码应该尽可能自解释。
  • Enumerating over an array using for...in... should be avoided.
  • 枚举一个数组,使用for…in…应该避免。
  • for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As javsacript is loosely typed and the for...in... can be handed any arbitory object to handle; it's safer to validate the property we're looking for is available.

    在…………应该验证枚举,以确保对象的枚举包含您要查找的属性。由于javpt是松散类型的,而for…可以交给任何仲裁对象处理;更安全的方法是验证我们正在寻找的属性是否可用。

    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);
    

#22


1  

hope this helps

希望这有助于

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

#23


1  

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

下面是我的变体,它允许以一种可移植的方式获取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;
};

Here's a CoffeeScript version of the same function:

这是同一功能的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

Example output for console.log(getLocalIPs())

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' } }

#24


1  

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);

#25


1  

One liner for MAC os first localhost address only.

When developing apps on mac os, and want to test it on the phone, and need your app to pick the localhost ip automatically.

当在mac os上开发应用程序时,想要在手机上测试它,并且需要你的应用程序自动选择本地主机ip。

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

这只是为了说明如何自动查找ip地址。要测试这个,你可以点击终端

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

output will be your localhost ip Address.

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

#26


1  

Here's a neat little one-liner for you which does this functionally:

这里有一个简洁的一行代码,它的功能是:

const ni = require('os').networkInterfaces();
Object
  .keys(ni)
  .map(interf =>
    ni[interf].map(o => !o.internal && o.family === 'IPv4' && o.address))
  .reduce((a, b) => a.concat(b))
  .filter(o => o)
  [0];

#27


1  

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

我只知道我希望IP地址从192.168开始。这个代码会告诉你:

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.

当然,如果你想换一个不同的数字,你可以改变数字。

#28


0  

I'm using node.js 0.6.5

我使用的节点。js 0.6.5

$ node -v
v0.6.5

Here is what I do

这就是我所做的

var util = require('util');
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
        util.puts(stdout);
}
exec("hostname -i", puts);

#29


0  

Here's a variation that allows you to get local ip address (tested on Mac and Win):

这里有一个变体,允许您获得本地ip地址(在Mac和Win上测试):


var
    // Local ip address that we're trying to calculate
    address
    // Provides a few basic operating-system related utility functions (built-in)
    ,os = require('os')
    // Network interfaces
    ,ifaces = os.networkInterfaces();


// Iterate over interfaces ...
for (var dev in ifaces) {

    // ... and find the one that matches the criteria
    var iface = ifaces[dev].filter(function(details) {
        return details.family === 'IPv4' && details.internal === false;
    });

    if(iface.length > 0) address = iface[0].address;
}

// Print the result
console.log(address); // 10.25.10.147

#30


0  

The bigger question is "Why?"

更大的问题是“为什么?”

If you need to know the server on which your NODE is listening on, you can use req.hostname.

如果您需要知道您的节点正在监听的服务器,您可以使用req.hostname。

#1


286  

'use strict';

var os = require('os');
var ifaces = os.networkInterfaces();

Object.keys(ifaces).forEach(function (ifname) {
  var alias = 0;

  ifaces[ifname].forEach(function (iface) {
    if ('IPv4' !== iface.family || iface.internal !== false) {
      // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
      return;
    }

    if (alias >= 1) {
      // this single interface has multiple ipv4 addresses
      console.log(ifname + ':' + alias, iface.address);
    } else {
      // this interface has only one ipv4 adress
      console.log(ifname, iface.address);
    }
    ++alias;
  });
});

// en0 192.168.1.101
// eth0 10.0.0.101

#2


196  

os.networkInterfaces as of right now doesn't work on windows. Running programs to parse the results seems a bit iffy. Here's what I use.

net接口目前还不能在windows上工作。运行程序来解析结果似乎有点不可靠。以下是我使用。

require('dns').lookup(require('os').hostname(), function (err, add, fam) {
  console.log('addr: '+add);
})

This should return your first network interface local ip.

这将返回您的第一个网络接口本地ip。

#3


100  

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

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

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

#4


37  

Any IP of your machine you can find by using the os module - and that's native to NodeJS

您可以通过使用os模块找到您的机器的任何IP——这是NodeJS的本地代码。

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

只需调用os. networkinterface(),就会得到一个易于管理的列表——比按联盟运行ifconfig要容易

http://nodejs.org/api/os.html#os_os_networkinterfaces

http://nodejs.org/api/os.html os_os_networkinterfaces

Best

最好的

Edoardo

Edoardo

#5


30  

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

这是节点的一个片段。用于解析ifconfig的输出并(异步地)返回发现的第一个IP地址的js代码:

(tested on MacOS Snow Leopard only; hope it works on linux too)

(只在MacOS雪豹上测试;希望它也适用于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 OSs without 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 IPs
            var matches = stdout.match(filterRE);
            // JS has no lookbehind REs, 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 exec a system call every time; otherwise the cached value is used.

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


Updated version

Returns an array of all local network addresses.

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

Tested on Ubuntu 11.04 and Windows XP 32

在Ubuntu 11.04和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);

#6


22  

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 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:

调用ifconfig是非常依赖于平台的,网络层确实知道套接字的ip地址,所以最好是问它。Node不会公开直接的方法,但是您可以打开任何套接字,并询问正在使用的本地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');
  });
}

Usage case:

使用情况:

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

#7


22  

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 IPs for multi-interface machines.

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

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';
}

#8


18  

Your local IP is always 127.0.0.1.

您的本地IP总是127.0.0.1。

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

然后是网络IP,可以从ifconfig (*nix)或ipconfig (win)获得。这只在本地网络中有用。

Then there is your external/public IP, 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.

然后是您的外部/公共IP,您只能通过某种方式向路由器请求它,或者您可以设置一个外部服务,该服务在收到请求时返回客户端IP地址。还有其他类似的服务,比如whatismyip.com。

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

在某些情况下(例如,如果您有一个广域网路连接),网络IP和公共IP是相同的,并且两者都可以用于外部以到达您的计算机。

If your network and public IPs are different, you may need to have your network router forward all incoming connections to your network ip.

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


Update 2013:

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.

现在有了一种新的方法,您可以检查连接的socket对象以获得一个名为localAddress的属性,例如net. socket.com .localAddress。它将返回套接字末尾的地址。

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

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


Update 2015:

2015年更新:

The previous doesn't work anymore.

前一个不再起作用了。

#9


15  

Install a module called ip like

安装一个名为ip like的模块

npm install ip

then use this code.

然后使用这段代码。

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

#10


8  

The correct one liner for both underscore and lodash is:

对于下划线和lodash,正确的一行是:

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

#11


8  

use npm ip module

使用npm ip模块

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'

#12


5  

Here's a simplified version in vanilla javascript to obtain a single ip:

这里有一个简化版本的香草javascript获得一个单一的ip:

function getServerIp() {

  var os = require('os');
  var ifaces = os.networkInterfaces();
  var 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';
}

#13


4  

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

对于任何对简洁感兴趣的人,以下是一些不需要插件/依赖的“一行程序”,它们不是标准节点安装的一部分:

Public IPv4 and IPv6 of eth0 as an Array:

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

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

First Public IP of eth0 (usually IPv4) as String:

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

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

#14


4  

for Linux and MacOS uses, if you want to get your IPs by a synchronous way, try this.

对于Linux和MacOS,如果您想通过同步方式获取IPs,可以尝试一下。

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' ]

#15


3  

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

基于上面的评论,以下是当前版本的Node:

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.

上面一个答案的注释忽略了对values()的调用。看起来os.networkInterfaces()现在返回一个对象,而不是数组。

#16


3  

Here is a variation of the above 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 then just pass null to get all, but you'll sort that out. You could also pass in another arg for the regex filter if so inclined to add

这里是上述例子的一个变体。它会过滤vMware接口等等。如果你不传递一个索引,它会返回所有地址,否则你可能想把它设为默认值为0,然后传递null来获取所有地址,但是你会把它分类。如果想要添加regex过滤器,也可以传递另一个arg。

    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;
}

#17


3  

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

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

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.

这比从os.networkInterfaces()或DNS主机名查找中选择接口更可靠。它可以忽略VMware虚拟接口、环回和VPN接口,并且可以在Windows、Linux、Mac OS和FreeBSD上运行。在引擎盖下面,它执行路线。exe或netstat并解析输出。

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

#18


2  

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).

谷歌在搜索“node”时将我引向了这个问题。js获取服务器ip”,所以让我们为那些试图在其节点中实现这一点的人提供一个替代答案。js服务器程序(可能是原始海报的情况)。

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 (eg. second parameter passed to the listen() function).

在服务器只绑定一个IP地址的最普通的情况下,不需要确定IP地址,因为我们已经知道将它绑定到哪个地址(例如)。传递给listen()函数的第二个参数。

In the less trivial case where the server is bound to multiple IPs 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.

在服务器绑定到多个IP地址的情况下,我们可能需要确定客户端连接的接口的IP地址。正如Tor Valamo所建议的,现在我们可以很容易地从连接的套接字和它的localAddress属性中获取这些信息。

For example, if the program is a web server:

例如,如果程序是web服务器:

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:

如果是通用的TCP服务器:

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:

更多细节,请参阅:

#19


2  

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);

#20


1  

Here is a multi-ip version of jhurliman's answer above:

以下是jhurliman的多重ip回答:

function getIPAddresses() {

    var ipAddresses = [];

    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) {
                ipAddresses.push(alias.address);
            }
        }
    }

    return ipAddresses;
}

#21


1  

I realise this is an old thread, but I'd like to offer an improvement on the top answer for the following reasons:

我意识到这是一个老问题,但我想在上面给出一个改进的答案,理由如下:

  • Code should be as self explanatory as possible.
  • 代码应该尽可能自解释。
  • Enumerating over an array using for...in... should be avoided.
  • 枚举一个数组,使用for…in…应该避免。
  • for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As javsacript is loosely typed and the for...in... can be handed any arbitory object to handle; it's safer to validate the property we're looking for is available.

    在…………应该验证枚举,以确保对象的枚举包含您要查找的属性。由于javpt是松散类型的,而for…可以交给任何仲裁对象处理;更安全的方法是验证我们正在寻找的属性是否可用。

    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);
    

#22


1  

hope this helps

希望这有助于

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

#23


1  

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

下面是我的变体,它允许以一种可移植的方式获取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;
};

Here's a CoffeeScript version of the same function:

这是同一功能的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

Example output for console.log(getLocalIPs())

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' } }

#24


1  

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);

#25


1  

One liner for MAC os first localhost address only.

When developing apps on mac os, and want to test it on the phone, and need your app to pick the localhost ip automatically.

当在mac os上开发应用程序时,想要在手机上测试它,并且需要你的应用程序自动选择本地主机ip。

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

这只是为了说明如何自动查找ip地址。要测试这个,你可以点击终端

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

output will be your localhost ip Address.

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

#26


1  

Here's a neat little one-liner for you which does this functionally:

这里有一个简洁的一行代码,它的功能是:

const ni = require('os').networkInterfaces();
Object
  .keys(ni)
  .map(interf =>
    ni[interf].map(o => !o.internal && o.family === 'IPv4' && o.address))
  .reduce((a, b) => a.concat(b))
  .filter(o => o)
  [0];

#27


1  

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

我只知道我希望IP地址从192.168开始。这个代码会告诉你:

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.

当然,如果你想换一个不同的数字,你可以改变数字。

#28


0  

I'm using node.js 0.6.5

我使用的节点。js 0.6.5

$ node -v
v0.6.5

Here is what I do

这就是我所做的

var util = require('util');
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
        util.puts(stdout);
}
exec("hostname -i", puts);

#29


0  

Here's a variation that allows you to get local ip address (tested on Mac and Win):

这里有一个变体,允许您获得本地ip地址(在Mac和Win上测试):


var
    // Local ip address that we're trying to calculate
    address
    // Provides a few basic operating-system related utility functions (built-in)
    ,os = require('os')
    // Network interfaces
    ,ifaces = os.networkInterfaces();


// Iterate over interfaces ...
for (var dev in ifaces) {

    // ... and find the one that matches the criteria
    var iface = ifaces[dev].filter(function(details) {
        return details.family === 'IPv4' && details.internal === false;
    });

    if(iface.length > 0) address = iface[0].address;
}

// Print the result
console.log(address); // 10.25.10.147

#30


0  

The bigger question is "Why?"

更大的问题是“为什么?”

If you need to know the server on which your NODE is listening on, you can use req.hostname.

如果您需要知道您的节点正在监听的服务器,您可以使用req.hostname。