-
-
Save rwat/581391 to your computer and use it in GitHub Desktop.
(ns your-namespace | |
(:use [clojure.string :only [split]])) | |
; authored by ordnungswidrig | |
(defn is-rfc1918? | |
"Returns true if a string is a dotted quad in the IP ranges of 10.0.0.0/8, | |
192.168.0.0/16 or 172.16.0.0/22, else returns nil)" | |
[^String ip] | |
(when-let [[a b c d :as qs] | |
(map #(Short/valueOf %) (clojure.string/split ip #"\."))] | |
(and (= 4 (count qs)) (every? #(<= 0 % 255) qs) | |
(or (= 10 a) | |
(= [192 168] [a b]) | |
(and (= 172 a) (<= 16 b 31)))))) | |
(prn (is-rfc1918? "10.123.45.6")) | |
(ns your-namespace
(:use [clojure.string :only [split]]))
(defn is-rfc1918?
(if-let [[a b c d :as qs] (map #(Byte/decode %) (clojure.string/split ip #"\."))]
(and (= 4 (count qs)) (every? #(<= 0 % 255) qs)
(or (= 10 a)
(= [192 168] [a b])
(and (= 172 a)
(<= 16 b 31)))))
(defn is-rfc1918?
"Returns true if a string is a dotted quad in the IP ranges of 10.0.0.0/8,
192.168.0.0/16 or 172.16.0.0/12, else returns nil"
[^String ip]
(let [ip-re #"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})"
octet-range (fn [x] (<= 0 x 255))]
(when-let [[_ a b c d] (re-matches ip-re ip)]
(and (every? octet-range [b c d])
(or (= 10 a)
(= [192 168] [a b])
(and (= 172 a) (<= 16 b 31)))))))
Try two
(defn is-rfc1918?
"Returns true if a string is a dotted quad in the IP ranges of 10.0.0.0/8,
192.168.0.0/16 or 172.16.0.0/12, else returns nil"
[^String ip](let [octet-range #%28<= 0 % 255%29)]
(when-let [[a b c d](map #%28Integer/parseInt %%29 %28clojure.string/split ip #"."%29)](and %28every? octet-range [b c d]%29
%28or %28= 10 a%29
%28= [192 168] [a b]%29
%28and %28= 172 a%29 %28<= 16 b 31%29%29%29))))
go with ordnungswidrig's new version it's more complete
Awesome learning experience provided to me by ordnungswidrig, grignaak, raek, and jkkramer. I changed what I had, wholesale, to ordnungswidrig's version. I so appreciate the learning I was able to do today and it wouldn't have been possible without the aforementioned teachers.
Updated - changed 'Byte/decode' to 'Integer/valueOf'. I had forgotten Java's Byte is signed so any valid octet value from 128 to 255 was throwing:
java.lang.NumberFormatException: Value X out of range from input X
java.lang.Short should do as well :-)
Thank you! I had forgotten about short / Short(s), too ; )
A Thank You goes out to raek and amalloy for explaining 'Truth and Sequences' to me. (JoC should use that as a title for a subchapter ; )