Convert IP addresses to integers

Convert IP addresses to integers

Here is an example of some Python code to convert IP addresses to their Packed (integer) form. Addresses in their packed form are useful when you need to calculate the first host, last host, or subnet addresses.

192.168.1.0
255.0.0.0
255.255.255.255
0.0.0.1
0.0.0.255
addresses.txt
#!/usr/bin/env python3


with open("addresses.txt", "r") as f:
        addresses = filter(None, f.read().split("\n"))


def ip_to_int32(ip):
        packed_int = [int(ip.split(".")[0]) << 24, int(ip.split(".")[1]) \
        << 16, int(ip.split(".")[2]) << 8, int(ip.split(".")[3])]
        return sum(packed_int)


for address in addresses:
        packed_ip = ip_to_int32(ip=address)
        print(packed_ip)
chmod +x ip_to_int.py
python3 ip_to_int.py


This was done through Prism.js

Show Comments