Today colleagues have a demand, hope that the Web server in the Nodejs of the corresponding site can support intranet access, and later found that the change in express hostname properties for their own intranet IP can be. But the problem is, our machines are automatically access to the intranet IP, then this time to write the death of the hostname next to basically can not use, so we thought of the dynamic access in the Nodejs intranet IP, and the value assigned to express open method on it, so I started with this idea.
We first understand how to obtain intranet IP, the general method on the internet I tried, in my machine is invalid, debugging to find it is not completely generic, so I for the company side of the intranet environment made changes.
On-line 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.A
ddress;
}
}); Ifaces[dev2].foreach (function (Details) {if (details.family = = ' IPv4 ') {ip2 = details
. Address;
}
});
if (null = IP | | null = = IP2) { Continue
///Add the record to the map if (Ip.indexof (' 10. ') = 0 | |
Ip.indexof (' 172. ') = = 0 | |
Ip.indexof (' Map.push. ') = = 0 ({"intranet_ip": IP, "internet_ip": Ip2});
else {Map.push ({"Intranet_ip": Ip2, "internet_ip": IP});
}} return map; } console.log (Getlocalip ());
Modified (is not much simpler, I just can use on the line, I this may not necessarily apply to you oh, but to give everyone a thought just)
var OS = require (' OS ');
Get intranet IP
function getlocalip () {
var map = [];
var ifaces = os.networkinterfaces ();
for (Var dev. ifaces) {
if (ifaces[dev][1].address.indexof (' 192.168 ')!=-1) {return
ifaces[dev][1].address;< c7/>}
} return
map;
Exports.getlocalip=getlocalip;
Next, modify the Hostnam properties of the Grunt Express module
Hostname:getlocalip ()
Done.