Skip to content Skip to sidebar Skip to footer

Convert Ip Address String To Binary In Python

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

Solution 1:

Is socket.inet_aton() what you want?

Solution 2:

You think of something like below ?

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

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

Solution 3:

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 python3import 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 numberprint(bin(int(ipaddress.IPv4Address('192.168.1.1'))))
# -> 0b11000000101010000000000100000001

Solution 4:

You can use string format function to convert the numbers to binary. I made this function:

defip2bin(ip):
    octets = map(int, ip.split('/')[0].split('.')) # '1.2.3.4'=>[1, 2, 3, 4]
    binary = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(*octets)
    range = int(ip.split('/')[1]) if'/'in ip elseNonereturn binary[:range] ifrangeelse binary

This will return a binary IP or IP range, so you can use it to test if an IP is in a range:

>>> ip2bin('255.255.127.0')
'11111111111111110111111100000000'>>> ip2bin('255.255.127.0/24')
'111111111111111101111111'>>> ip2bin('255.255.127.123').startswith(ip2bin('255.255.127.0/24'))
True

Solution 5:

Define IP address in variable

ipadd = "10.10.20.20"

convert IP address in list

ip = ipadd.split(".")

Now convert IP address in binary numbers

print ('{0:08b}.{1:08b}.{2:08b}. 
    {3:08b}'.format(int(ip[0]),int(ip[1]),int(ip[2]),int(ip[3])))

00001010.00001010.00010100.00010100

Post a Comment for "Convert Ip Address String To Binary In Python"