简体   繁体   中英

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

Is socket . inet_aton() what you want?

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

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.

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

def ip2bin(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 else None
    return binary[:range] if range else 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

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
IP = '192.168.1.1'

ip2bin =  ".".join(map(str,["{0:08b}".format(int(x)) for x in IP.split(".")]))
print(ip2bin)

output

11000000.10101000.00000001.00000001

ip = '192.168.1.1'

k=[" "]

for x in ip.split("."):

   a=(bin(int(x))[2:])
   k.append(a)    

print(".".join(list(k))[2:])

Should I be looking at netaddr, sockets, or something completely different?

For anyone asking in the present day, you should use netaddr if you want to do anything not supported in the Python 3.3+ built-in ipaddress module. Here is how you would do what you wanted to with netaddr , as an example:

>>> from netaddr import IPAddress
>>> ip = IPAddress('192.168.1.1')
>>> print(ip.bits())
11000000.10101000.00000001.00000001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM