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
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.
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 (eg. second parameter passed to the
listen()
function).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.For example, if the program is a web server:
And if it's a generic TCP server:
When running a server program, this solution offers very high portability, accuracy and efficiency.
For more details, see:
Here's a simplified version in vanilla javascript to obtain a single ip:
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 executesroute.exe
ornetstat
and parses the output.The correct one liner for both underscore and lodash is:
I was able to do this using just node js
As Node JS
As bash script (needs node js installed)