IP representation

August 9, 2010

[Warning: This post is a backup recovery from my previous Wordpress blog. All content was automatically converted accessing a MySQL database using a Python script (details). Mostly are in Portuguese but if you are interest I can translate to English. If you found any problem dont’t hesitate to contact me in comments.]

Yesterday I came across with an interesting contruction for IP address. Suppose that you want store the address '192.168.10.33' no matter the dot.

192<<24|168<<16|10<<8|33

That produces

3232238113 (0xc0a80a21)

To return is just get the address in hex format and split in 4 sections. Means that: c0 (192) a8 (168) 0a (10) 21 (33). An example using Python generators to return using big endian format (download).

def octet(ip):         for i in range(-24,8,8):                 yield ip >> -i & 0xff

And got each value:

r = octet(ip) r.next() # returns 192 r.next() # returns 168 r.next() # returns 10 r.next() # returns 33