nodejs: nodeのipv4 addressを調べる

1.nodeのipv4 addressを調べる
defaultでは、maskが24 bitのものを、terminalのipv4 address としている

2.code

const os = require('os');
const net = os.networkInterfaces();

console.log(ip());

function ip (_mask) {
const mask = _mask || 24;

    for(let key in net) {
        for(let key2 in net[key]) {
            for(let key3 in net[key][key2]) {
                if(key3 == "cidr") {
                    if(net[key][key2][key3].indexOf("/") !==-1) {
                        let ip = net[key][key2][key3].split("/");
                        if(ip[1] == mask) {
                            return ip[0];
                        }
                    }
                }
            }
        }
    }
}

2.実行結果

# node ip.js
192.168.1.125