NL IP Address Calculator?

Started by ax0n, March 04, 2008, 08:09:20 AM

Previous topic - Next topic

ax0n

I'm having some trouble figuring out some stuff.



The first thing is netmask.  If I have 192.168.0.49/24, I'm tempted to try this to turn /24 into a network mask:



(link posted to log because I can't get the code to show up right)



http://stuff.h-i-r.net/nl2.txt">http://stuff.h-i-r.net/nl2.txt





How do I limit hex to only 32 bits (i.e. 0xffffff00 instead of 0xffffffff00) ???



Also, do you know of a good way to take a 32-bit number and make it into an IP address in dotted decimal notation?



T.I.A.



--ax0n

http://www.h-i-r.net/">http://www.h-i-r.net/

Elica

#1
Quote from: "ax0n"
How do I limit hex to only 32 bits (i.e. 0xffffff00 instead of 0xffffffff00) ???

If hex is a number, truncate (clear) all bits above 32-nd.
(set 'hex 0xffeeddccbbaa)
(format "%x" (& hex 0xffffffff))



Quote from: "ax0n"Also, do you know of a good way to take a 32-bit number and make it into an IP address in dotted decimal notation?

Not experienced in newLisp, but this should do the job:
(set 'addr 0xffaa0410)

(string
  (mod (/ addr 0x1000000) 0x100) "."
  (mod (/ addr 0x10000) 0x100) "."
  (mod (/ addr 0x100) 0x100) "."
  (mod addr 0x100)
)

Elica

#2
And here is a lispish variant that takes and prints only the last 4 bytes:
(define (ip4 addr (level 4))
  (if (> level 1)
    (string
       (ip4 (/ addr 256) (- level 1))
       "." (mod addr 256))
    (mod addr 256)
  )
)


(ip4 0xff01a00210)

"1.160.2.16"

ax0n

#3
Awesome, I didn't even think to AND it against 0xffffffff even though as part of this calculator I will have to AND the IP against the netmask to come up with the network address, so I'm not sure why that logic did 't come to me earlier.  



That helps leaps and bounds.

Lutz

#4
... here is yet another way to convert from IP-no to string:


(set 'addr 0xffaa0410)

(format "%d.%d.%d.%d" (unpack "bbbb" (pack ">lu" addr)))

=> "255.170.4.16"


be aware of correct byte-order you may have to change the ">lu" to a "<lu" on big endian CPUs

Elica

#5
http://forum.skycode.com/img/133.gif">http://forum.skycode.com/img/133.gif">http://forum.skycode.com/img/133.gif">

Vir sapit qui pauca loquitur

ax0n

#6
I posted the following article.  Thanks for your help, guys!



http://www.h-i-r.net/2008/03/ip-subnetting-more-fun-with-newlisp.html">http://www.h-i-r.net/2008/03/ip-subnett ... wlisp.html">http://www.h-i-r.net/2008/03/ip-subnetting-more-fun-with-newlisp.html