tags:

views:

77

answers:

4

I want to convert an ip address read from a file in the decimal format (192.168.65.72) to one in binary format {110000001010100001000001010001000}.I am reading the ip address in the decimal format from a file.Find the code snippet below.

/*contains 192.168.65.72*/
filter = open("filter.txt", "r")

for line in filter:
    bytePattern = "([01]?\d\d?|2[0-4]\d|25[0-5])"
    regObj = re.compile("\.".join([bytePattern]*4))
    for match in regObj.finditer(line):
        m1,m2,m3,m4 = match.groups()
        print "%s %s %s %s" %(m1, m2, m3, m4)

I want to convert m1,m2,m3 and m4 each into an 8bit binary value.I cannot figure out a way to do that.I am new to python.Any help will be greatly appreciated.

Cheers.

+1  A: 
>>> bin( 192 )
'0b11000000'

String manipulation does the rest. Note however that in an IP all but the first parts are allowed to be zero.

poke
+2  A: 
''.join([ bin(int(x))[2:].rjust(8,'0') for x in '123.123.123.123'.split('.')])
TheMachineCharmer
Be careful about required padding. Each byte in the IP needs to be represented by 8 bit, regardless of the value.
poke
@poke oh yes thanks for reminding :) I do it now.
TheMachineCharmer
`''.join([bin(256 + int(x))[3:] for x in '123.123.123.123'.split('.')])`
Omnifarious
@Omnifarious `bin(256 + int(x)` this is one god damn good idea :) +1
TheMachineCharmer
I am a python newbie.I tried the above thing but it givesNameError: name 'bin' is not defined.I googled bin function in python and came to know that it was a part of the python standard library.do i need to import any other package to get the python standard library?Also what is the variable x supposed to mean? in the above explanation.It may not be the most intelligent question in the world but I do not understand it.Thank very much in advance.Cheers,liv2hak
liv2hak
1. No,you need not import anything to get `bin`. 2. What is used in above answer is called *list comprehension*. You can read http://docs.python.org/tutorial/datastructures.html#list-comprehensions.If you don't understand something please let me know.Best of luck!
TheMachineCharmer
thank you very much.I am able to get the desired output.cheers.
liv2hak
+1  A: 

If you want a string containing the raw data for the 32 bit IP address:

import struct
struct.pack('4B', *(int(x) for x in '123.123.123.123'.split('.'))

Or if you want a 32-bit integer containing the IP address:

import struct
struct.unpack('>I', struct.pack('4B', *(int(x) for x in '123.123.123.123'.split('.')))
Omnifarious
+1  A: 

Convert an IPv4 address from dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format:

socket.inet_aton("192.168.65.72")

Matt Joiner