Friday, May 3, 2013

Clojure: What is my IP address?

I needed to get the IP address of the current host and came across an article Detect your host IP with Clojure which had some good ideas. Unfortunately, this code does not take into account some of issues like network interfaces that are not up. My box is a Windows 7 64-bit box with VirtualBox installed as well as sometimes being docked and sometimes working wirelessly. Using that code as a base, I wrote this code:
(import (java.net NetworkInterface Inet4Address))
(defn ip-filter [inet]
(and (.isUp inet)
(not (.isVirtual inet))
(not (.isLoopback inet))))
(defn ip-extract [netinf]
(let [inets (enumeration-seq (.getInetAddresses netinf))]
(map #(vector (.getHostAddress %1) %2) (filter #(instance? Inet4Address %) inets ) (repeat (.getName netinf)))))
(defn ips []
(let [ifc (NetworkInterface/getNetworkInterfaces)]
(mapcat ip-extract (filter ip-filter (enumeration-seq ifc)))))
view raw ip.clj hosted with ❤ by GitHub
This code returns a seq of vectors of IP address and the interface name. It only returns interfaces that are up and are not the loopback.