usr bin env python3 Converts IP PREFIX lines from stdin and input file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python3
# Converts IP/PREFIX lines from stdin and input files
# to stdout in P2P Block format suitable for import
# into Torrent clients such as qBitTorrent.
#
# Originally posted here:
# https://www.reddit.com/r/torrents/comments/bdme4i
from fileinput import input
import ipaddress
i = 1
for line in input():
candidate = line.strip()
try:
network = ipaddress.ip_network(candidate)
except ValueError:
continue
else:
if network.prefixlen < 32:
hosts = network.hosts()
first_ip = next(hosts)
last_ip = (first_ip + (network.num_addresses - 3))
elif network.prefixlen == 32:
first_ip = network.network_address
last_ip = first_ip
else: # shouldn't get here
continue
print('net{}:{}-{}'.format(i, first_ip, last_ip))
i += 1