Skip to content

Instantly share code, notes, and snippets.

@zentrope
Created September 10, 2013 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zentrope/6516974 to your computer and use it in GitHub Desktop.
Save zentrope/6516974 to your computer and use it in GitHub Desktop.
Some to/from inet address + cidr utilities.
(ns utils)
;;-----------------------------------------------------------------------------
;; Utils
(defn- expt
[x pow]
(apply * (repeat pow x)))
(defn- shft
[num to]
(bit-shift-right (bit-and num (bit-shift-left 0xff to)) to))
;;-----------------------------------------------------------------------------
;; Interface
(defn ip->num
[[a b c d]]
(+ (* a (expt 256 3))
(* b (expt 256 2))
(* c 256)
d))
(defn num->ip
[num]
[(shft num 24)
(shft num 16)
(shft num 8)
(bit-and num 0xFF)])
(defn cidr->ips
[a b c d len]
(let [nw (ip->num [a b c d])
mask (bit-shift-left -1 (- 32 len))
low (bit-and nw mask)
high (+ low (bit-not mask))]
[low high]))
(defn in-cidr-range?
[[a b c d len] [w x y z]]
(let [[low high] (cidr->ips a b c d len)
val (ip->num [w x y z])]
(and (>= val low)
(<= val high))))
(defn gen-ip
([]
(gen-ip []))
([quads]
(loop [q quads]
(if (= (count q) 4)
q
(recur (conj q (rand-int 256)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment