Sorting IP addresses in Python

Trying to sort by IP addresses using their regular string values doesn’t work very well:

sorted(['192.168.1.1','192.168.2.1','192.168.11.1','192.168.12.1'])
['192.168.1.1', '192.168.11.1', '192.168.12.1', '192.168.2.1']

Good news is the solution isn’t difficult. Just use ip_address() to get the IP in integer format with a lambda:

import ipaddress

ips = ['192.168.1.1','192.168.2.1','192.168.11.1','192.168.12.1']

sorted(ips, key=lambda i: int(ipaddress.ip_address(i)))

Results in the following:

['192.168.1.1', '192.168.2.1', '192.168.11.1', '192.168.12.1']

In a more complex example where the data is in a list of dictionaries:

import ipaddress

ips = [
  {'address': "192.168.0.1"},
  {'address': "100.64.0.1"},
  {'address': "10.0.0.1"},
  {'address': "198.18.0.1"},
  {'address': "172.16.0.1"},
]

addresses = sorted(ips, key=lambda x: int(ipaddress.ip_address(x['address'])))

print(addresses)

Results in the following:

[{'address': '10.0.0.1'}, {'address': '100.64.0.1'}, {'address': '172.16.0.1'}, {'address': '192.168.0.1'}, {'address': '198.18.0.1'}]

To get the IPs with highest first, just add reverse=True to the sorted() call

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s