Get Intranet IP address in nodejs, and nodejs get IP Address
Today, my colleague has a demand that the website corresponding to the web server in nodejs can support Intranet access. Later I found that I could modify the hostname attribute in express to my Intranet ip address. However, the problem is that all our machines automatically obtain the Intranet ip address, so this write-down hostname will basically be unavailable next time, so we thought of dynamically obtaining the Intranet ip address in nodejs, and assign the value to the open method of express, so I started the work according to this idea.
We first learned how to obtain the Intranet ip address. I tried the general method on the Internet and it was invalid on my machine. After debugging, I found that it was not completely universal, so I made changes to the company's Intranet environment.
Common online writing:
Var OS = require ('OS'); function getLocalIP () {var map = []; var ifaces = OS. networkInterfaces (); console. log (ifaces); for (var dev in ifaces) {if (dev. indexOf ('eth0 ')! =-1) {var tokens = dev. split (':'); var dev2 = null; if (tokens. length = 2) {dev2 = 'eth1: '+ tokens [1];} else if (tokens. length = 1) {dev2 = 'eth1';} if (null = ifaces [dev2]) {continue ;} // find the ip address var ip of eth0 and eth1 respectively = null, ip2 = null; ifaces [dev]. forEach (function (details) {if (details. family = 'ipv4 ') {ip = details. address ;}}); ifaces [dev2]. forEach (function (details) {if (details. family = 'ipv4 ') {ip2 = details. address ;}}); if (null = ip | null = ip2) {continue;} // Add record to map to if (ip. indexOf ('10. ') = 0 | ip address. indexOf ('2017. ') = 0 | ip address. indexOf ('2017. ') = 0) {map. push ({"intranet_ip": ip, "internet_ip": ip2});} else {map. push ({"intranet_ip": ip2, "internet_ip": ip}) ;}} return map;} console. log (getLocalIP ());
After modification (is it much simpler? I just want to use it. I don't necessarily apply to you, but I just want to give you some ideas)
Var OS = require ('OS'); // obtain the Intranet ipfunction getLocalIP () {var map = []; var ifaces = OS. networkInterfaces (); for (var dev in ifaces) {if (dev. indexOf ('local connection ')! =-1) {return ifaces [dev] [1]. address ;}} return map ;}
Next, modify the hostnam attribute of the Grunt express module.
Hostname: getLocalIP ()
Success!