Search code examples
python-3.xbinaryipv4octetstring

How does one convert a binary IPv4 address to 4 octets using the Python3 ipaddress library?


I want to use the Python3 library ipaddress to convert a binary IPv4 network address into 4 octets; how would I do that?

Example:

1100 0000 - 1010 1000 - 0000 0000 - 0000 0000

to

192.168.0.0

Solution

  • I don't think there is a straightforward way, especially not if the input is in such a weird format. Convert each "octat" to decimal:

    import ipaddress
    
    weird_ip = '1100 0000 - 1010 1000 - 0000 0000 - 0000 0000'
    print(ipaddress.IPv4Address('.'.join(str(int(''.join(i.split(' ')), base=2))
                                for i in weird_ip.split(' - '))))
    

    Outputs

    192.168.0.0