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
Define IP address in variable
convert IP address in list
Now convert IP address in binary numbers
ipaddr
(see PEP 3144):In Python 3.3,
ipaddress
module:To match the example in your question exactly:
Is socket.
inet_aton()
what you want?You can use string format function to convert the numbers to binary. I made this function:
This will return a binary IP or IP range, so you can use it to test if an IP is in a range:
You think of something like below ?
I agree with others, you probably should avoid to convert to binary representation to achieve what you want.
output