Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IP address string to binary in Python

Tags:

python

binary

ip

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

like image 921
pizzim13 Avatar asked Apr 28 '10 23:04

pizzim13


People also ask

How do you convert an IP address to binary notation?

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.

Can we convert string to binary in Python?

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) .

How do you convert data to binary in Python?

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.

Can you convert float to binary in Python?

Python doesn't provide any inbuilt method to easily convert floating point decimal numbers to binary number.


2 Answers

Is socket.inet_aton() what you want?

like image 140
EMP Avatar answered Oct 09 '22 18:10

EMP


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.

like image 33
kriss Avatar answered Oct 09 '22 18:10

kriss