Getting IP of an Interface in Clojure

Here’s a rather crude way in clojure to get the IP of the current host given a network interface

1
2
3
4
5
6
(defn ip-for-interface [interface]
  (first (->> (java.net.NetworkInterface/getByName interface)
              .getInetAddresses
              enumeration-seq
              (filter #(instance? java.net.Inet4Address %1))
              (map #(.getHostAddress %1)))))

Of course, fails horribly with an NullPointerException if the interface is not present :)

Comments