fsociety001
fsociety001

Reputation: 11

Python3 sort IP addresses 4, 6 and Hostnames

I am looking at writing a function which sorts IP address (both IPv4 & 6) along with hostnames. e.g.

127.0.0.1
test.com
10.10.23.4
98.137.246.8
2001:0db8:85a3:0000:0000:8a2e:0370:7334
98.137.246.7

I have already tried this code, which only works for IPv4. Could somebody help write a function to sort all if they exist?

sorted(sorted_ips, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0])

The output should be, therefore sorting in ascending order of addresses.

10.10.23.4
98.137.246.7
98.137.246.8
2001:0db8:85a3:0000:0000:8a2e:0370:7334
test.com

Thanks in advance.

Upvotes: 0

Views: 241

Answers (1)

Chris
Chris

Reputation: 29742

One way using ipaddress.ip_address:

from ipaddress import ip_address

def ipsorter(s):
    try:
        ip = int(ip_address(s))
    except ValueError:
        return (1, s)
    return (0, ip)

sorted(l, key=ipsorter)

Output:

['10.10.23.4',
 '98.137.246.7',
 '98.137.246.8',
 '127.0.0.1',
 '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
 'test.com']

Upvotes: 1

Related Questions