i am looking for a command that can sort a file (or stream from stdin to stdout) much like the posix/unix/linux sort command, but based on the key being an IP address. bonuses: can you do it with just modules that come with Python? can you include support for IPv6?
A list to test would make it easier.
Here something I threw together. Might get you started.
ip_address = [
'192.168.0.1',
'192.168.0.5',
'20.101.24.5',
'101.17.31.8',
'41.37.101.40',
'41.37.101.4'
]
def sort_ip(key):
if key.count('.') == 3:
return 4, [k.rjust(3) for k in key.split('.')]
else:
# need more data for dealing with ipv6 address
return 6, [k.rjust(4) for k in key.split(':')]
def main():
ip_address.sort(key=sort_ip)
for ip in ip_address:
print(ip)
main()
needs to be able to sort a file. what if the file is massively huge (larger than available virtual memory)?
how does your code compare fc00::1 with fc00:0:2::1 ?
how does your code deal with addresses like: fc00::1.2.3.4 ?
Use
ipaddress module,handles IPv4 and IPv6 addresses.
>>> import ipaddress
>>> ip_1 = ipaddress.ip_address('fc00::1')
>>> ip_2 = ipaddress.ip_address('fc00:0:2::1')
>>> ip_1 < ip_2
True
Address and Network objects are not sortable by default.
If still need to do it there is
ipaddress.get_mixed_type_key
that be used as a key in
sorted()
.
import ipaddress
>>> ip_1 = ipaddress.ip_address('fc00::9')
>>> ip_2 = ipaddress.ip_address('fc00::5')
>>> ip_3 = ipaddress.ip_address('fc00::3')
>>> ip_4 = ipaddress.ip_address('fc00::100')
>>> sorted([ip_1, ip_2, ip_3, ip_4], key=ipaddress.get_mixed_type_key)
[IPv6Address('fc00::3'), IPv6Address('fc00::5'), IPv6Address('fc00::9'), IPv6Address('fc00::100')]
what about all the ips in fc00:/7 (fc00:: to fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff)?
what about any ipv6 (in ::/0)
is module ipaddress in Python2.6? 3.4? 3.3?
(Oct-23-2017, 07:46 AM)Skaperen Wrote: [ -> ]what about all the ips in fc00:/7 (fc00:: to fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff)?
what about any ipv6 (in ::/0)
The module follow the standard in
RFC 4291.
(Oct-23-2017, 07:46 AM)Skaperen Wrote: [ -> ]is module ipaddress in Python2.6? 3.4? 3.3?
It's
backport to 2.6.