Last active
March 18, 2019 02:53
-
-
Save v0lkan/21849685926ddbb8ca83e0b62b379b4f to your computer and use it in GitHub Desktop.
Returns the non-local network IPv4 interaces on the machine as an Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const os = require('os'); | |
// for lo-dashers: | |
// _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address'); | |
// should give a similar output. | |
// | |
// or for burrito-lovers: | |
// pluck(query(flatten(values(os.networkInterfaces())))({family: 'IPv4', internal: false}))('address'); | |
// | |
// or for ramda-lovers: | |
// R.compose(R.filter(R.propEq('family', 'IPv4')), R.flatten, R.values); | |
// | |
// or for clojuristas: | |
// #clojurescript #lumo lumo -e "(require '[os]) (let [s (js->clj (os.networkInterfaces) | |
// :keywordize-keys true)] (flatten (map (fn [[k v]] (reduce (fn [intf m] (if (and | |
// (not (:internal m)) (= (:family m) \"IPv4\")) (conj intf {k (:address m)}) intf)) [] v)) s))) | |
const ifaces = () => { | |
const osNetworkInterfaces = os.networkInterfaces(); | |
return Object.values(osNetworkInterfaces).reduce( | |
(acc, value) => value.reduce((acc2, interfaceDetails) => { | |
if ( | |
interfaceDetails.family === 'IPv4' && | |
!interfaceDetails.internal | |
) { | |
acc2.push(interfaceDetails.address); | |
} | |
return acc2; | |
}, acc), | |
[] // `acc` and `acc2` actually refer to this `[]` seed value. | |
// We populate it, and then return it as the response. | |
// | |
// If you are not an “ivory tower” funcionalista, we | |
// can consider this function “pure” for practical purposes | |
// because `[]` is a locally-initiated variable and it is | |
// not causing any external side-effect. | |
// | |
// Technically `os.networkInterfaces()` has a side effect | |
// but since it will almost always return the same result | |
// (unless you are using a dynamic DNS or somehting) | |
// you can consider it as a “constant” | |
// (again, for “practical” purposes) | |
// and ignore its side effect. | |
); | |
}; | |
// This will log something like “["10.20.160.251", "192.168.1.18"]” | |
console.log(ifaces()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like this clojurescript better for the results you are looking at