Convert IP address string to binary in Python

Purpose being to later calculate the broadcast address for Wake on LAN traffic

ipaddr (see PEP 3144):

import ipaddr

print ipaddr.IPNetwork('192.168.1.1/24').broadcast
# -> 192.168.1.255

In Python 3.3, ipaddress module:

#!/usr/bin/env python3
import ipaddress

print(ipaddress.IPv4Network('192.162.1.1/24', strict=False).broadcast_address)
# -> 192.168.1.255

To match the example in your question exactly:

# convert ip string to a binary number
print(bin(int(ipaddress.IPv4Address('192.168.1.1'))))
# -> 0b11000000101010000000000100000001

Is socket.inet_aton() what you want?


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.

Tags:

Python

Ip

Binary