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
Install a module called ip like
then use this code.
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:
Usage case:
I realise this is an old thread, but I'd like to offer an improvement on the top answer for the following reasons:
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.
use npm ip module
I'm using node.js 0.6.5
Here is what I do
Any IP of your machine you can find by using the os module - and that's native to NodeJS
All you need to do is call os.networkInterfaces() and you'll get an easy manageable list - easier than running ifconfig by leagues
http://nodejs.org/api/os.html#os_os_networkinterfaces
Best
Edoardo