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
Convert IPv4 dotted decimal to binary 1.1 IP address to binary. Take the octets -- the numbers between the decimal points -- one at a time, like this: 1 decimal = 00000001 binary. 1 decimal = 00000001 binary.
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
Python doesn't provide any inbuilt method to easily convert floating point decimal numbers to binary number.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With