Skip to content

Instantly share code, notes, and snippets.

@v0lkan
Last active March 18, 2019 02:53
Show Gist options
  • Save v0lkan/21849685926ddbb8ca83e0b62b379b4f to your computer and use it in GitHub Desktop.
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
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());
@gaberger
Copy link

I like this clojurescript better for the results you are looking at

(some->>
 (js->clj (os.networkInterfaces) :keywordize-keys true)
 (mapv
  (fn [[k v]]
    (reduce-kv
      (fn [c k v]
        (if (and (not (:internal v))
                 (and (= (:family v) "IPv4")))
            (conj c  (:address v))
            c))
     []
     v)))
 (remove empty?)
 flatten
 clj->js)

@v0lkan
Copy link
Author

v0lkan commented Mar 18, 2019

Yep that looks more concise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment