Created
September 10, 2013 23:01
-
-
Save zentrope/6516974 to your computer and use it in GitHub Desktop.
Some to/from inet address + cidr utilities.
This file contains 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
(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