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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
https://github.com/indutny/node-ip
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
Here's my variant that allows getting both IPv4 and IPv6 addresses in a portable manner:
Here's a CoffeeScript version of the same function:
Example output for
console.log(getLocalIPs())
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.This should return your first network interface local ip.
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...
Here is a snippet of node.js code that will parse the output of
ifconfig
and (asynchronously) return the first IP address found:(tested on MacOS Snow Leopard only; hope it works on linux too)
Usage example:
If the second parameter is
true
, the function will exec 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 and Windows XP 32
Usage Example for updated version