Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting IP Addresses in a Python Script

Tags:

python

sorting

I'm trying to sort IP Addresses which I'm reading into a python script and printing out. The code that I've drafted up reads and prints the contents of a file (see example)

#!/usr/bin/python

f = open('file.txt', 'r')
file_contents = f.read()
print (file_contents)
f.close()

My issue is how do I take that importing of IP Addresses and sort them correctly? At the command line I would normally pass the file through a simple sort command (sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 ). But how can I get python to sort the IPs it's reading from the file so the output is sorted correctly, taking into consideration the 0-255 numbering schema for each octet of an IP?

Thanks,

like image 801
Alby Avatar asked Oct 29 '25 17:10

Alby


1 Answers

You can use the built-in ipaddress module:

#!/usr/bin/python
import ipaddress

with open('file.txt', 'r') as f:
   ips = sorted(ipaddress.ip_address(line.strip()) for line in f)
   print('\n'.join(map(str, ips)))

If you're using an older Python version (before 3.3), you may need my backport. Also note that this code employs the with statement for file I/O, as this handles errors correctly.

With ipaddress, the IP addresses are actually tested for validity. Also, the code can correctly handle IPv6 addresses (i.e. ::1.2.3.4 > 000::12a0) as well as esoteric representations such as 2130706433, although you cannot mix IPv4 and IPv6 addresses.

Alternatively, you can use a natural sort algorithm. This will not verify the addresses and may be incorrect, but works as long as you input is always IPv4 addresses in the form 1.2.3.4.

like image 131
phihag Avatar answered Oct 31 '25 06:10

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!