Today, colleagues have a demand, hope that the Web server in the Nodejs of the corresponding site can support intranet access, and later found to modify the hostname attribute in Express for their own intranet IP can be. But the problem is that our machines are automatically acquired intranet IP, then this time the death of the hostname will not be able to use the next time, so we think of the Nodejs in the dynamic acquisition of the intranet IP, and the value of the open method of the express can be, so I follow this idea to start.
We first understand how to obtain the network IP, the general method of the Internet I tried, in my machine is invalid, debugging the next only to find it this is not completely generic, so I aimed at the company side of the intranet environment has been modified.
Web-based general wording:
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 eth0 and eth1 respectively IP var ip = null, IP2 = NULL; Ifaces[dev].foreach (function (Details) {if (details.family = = ' IPv4 ') {IP = Details.add Ress } }); Ifaces[dev2].foreach (function (Details) {if (details.family = = ' IPv4 ') {ip2 = DETAILS.A ddress; } }); if (null = = IP | | null = = IP2) {continue; }//Add the record to the map if (Ip.indexof (' 10. ') = = 0 | | Ip.indexof (' 172. ') = = 0 | | Ip.indexof (' 192. ') = = 0) {Map.push ({"intranet_ip": IP, "internet_ip": Ip2}); } else {Map.push ({"Intranet_ip": Ip2, "internet_ip": IP}); }}} return map;} Console.log (Getlocalip ());
Modified (is not a lot of simple, I just can use on the line, I this may not apply to you oh, just give everyone a train of thought only)
var OS = require (' OS ');//Get 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 properties of the Grunt Express module
Hostname:getlocalip ()
Done!
Get the intranet IP address in Nodejs