IP Subnetting - more fun with newLISP

I decided it would be fun to try to make an IP subnet calculator with newLISP.

Thanks to Elica and Lutz on the newLISP discussion boards. I needed some help with the logic. There's probably a way to compact this code down to about 3 lines somehow, but I'm still a newLISP n00b. I stuck with the logic examples that I have a firm understanding of, but the discussion yielded some interesting results.

Here's what I came up with

# newLISP IP Address calculator by ax0n
# ax0n (at) h-i-r.net
(define (iptostr ip4)
# Converts an integer to an IP in dotted decimal notation
(mod (/ ip4 0x1000000) 0x100) "."
(mod (/ ip4 0x10000) 0x100) "."
(mod (/ ip4 0x100) 0x100) "."
(mod ip4 0x100))

(define (iptonum ip4str)
# Converts an IP string to an integer
(map set '(one two three four) (parse ip4str "."))
(+ (* 0x1000000 (float one)) (* 0x10000 (float two))
(* 0x100 (float three)) (float four))

(< (length (main-args)) 3)
# Display usage if no args passed
(println "usage: ipcalc.lsp ip-address/maskbits")
(println "ex: ipcalc.lsp")
(set 'ipstr (last(main-args)))
(map set '(ipaddr bits) (parse ipstr "/"))
(set 'binip (iptonum ipaddr))
(set 'netmask (& 0xffffffff ( << 0xffffffff (- 32 (int bits)))))
(set 'netaddr (& binip netmask))
(set 'bcast (& 0xffffffff (| binip (~ netmask))))
(println "host IP: " ipaddr )
(println "netmask: " (iptostr netmask) )
(println "network: " (iptostr netaddr) )
(println "broadcast: " (iptostr bcast))
(println "Host range: " (iptostr (+ netaddr 1))" - "(iptostr (- bcast 1)))

Running it by itself gives you a syntax help page.

-bash-3.2$ ./ipcalc.lsp
usage: ipcalc.lsp ip-address/maskbits
ex: ipcalc.lsp

You have to provide an IP Address and mask in CIDR Notation. It does the rest!

-bash-3.2$ ./ipcalc.lsp
host IP:
Host range: -

You can download the script here:

blog comments powered by Disqus