tags:

views:

295

answers:

3

As part of a larger application, I am trying to convert an IP address to binary. Purpose being to later calculate the broadcast address for Wake on LAN traffic. I am assuming that there is a much more efficient way to do this then the way I am thinking. Which is breaking up the IP address by octet, adding 0's to the beginning of each octet where necessary, converting each octet to binary, then combining the results. Should I be looking at netaddr, sockets, or something completely different?

Example: From 192.168.1.1 to 11000000.10101000.00000001.00000001

A: 

Is socket.inet_aton() what you want?

Evgeny
It seems to work: `bin(struct.unpack('!I', socket.inet_aton('192.168.1.1'))[0])` -> `'0b11000000101010000000000100000001'`
J.F. Sebastian
A: 

ipaddr (see PEP 3144):

import ipaddr

print ipaddr.IPNetwork('192.168.1.1/24').broadcast
# -> 192.168.1.255
J.F. Sebastian
+1  A: 

You think of something like below ?

ip = '192.168.1.1'
print '.'.join([bin(int(x)+256)[3:] for x in ip.split('.')])

I agree with others, you probably should avoid to convert to binary representation to achieve what you want.

kriss
That's what I was looking for but, I don't fully understand how it works. I get that you are splitting the ip address by '.', then joining the results by a '.', and converting from a integer to binary but this: "(x)+256)[3:] for x in", completely lost. Can you point in the right direction to look up what you are doing?
pizzim13
@pizzim13: no magick. You understood well how it works. The +256 is there to always have a 9 bits binary number, then it's easy to remove 0b1 at front of the number.
kriss
@pizzim13: and for the `[... for x in ... ]` part look at **list comprehension** in python documentation.
kriss