Created
September 15, 2010 20:17
-
-
Save rwat/581391 to your computer and use it in GitHub Desktop.
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 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")) | |
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 ; )
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
go with ordnungswidrig's new version it's more complete