Author: Malte Bublitz
Language/File type: Python 3
Description
Calculate IPv4 subnet information based on a given network in CIDR format.
- Broatcast address
- Netmask
- List of IP addresses reachable from that network
Code
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
import sys, os
from pprint import pprint
import netaddr
def getNetwork() -> str:
print("Please enter a IPv4 network in CIDR notation, for example \"10.13.37.1/28\":")
print("? ", end="")
net = input()
if len(net) > 0:
return net
else:
# Example network as default
return "192.168.1.2/29"
sys.exit(1)
def main(net_cidr):
net = netaddr.IPNetwork(net_cidr)
print()
net_ips = []
for ip in net.iter_hosts():
net_ips.append(ip)
print("Network => netaddr." + repr(net))
print("IP => " + str(net.ip))
print("Netmask => " + str(net.netmask))
print("Broadcast => " + str(net.broadcast))
print("CIDR => " + str(net.cidr))
print("IPs in Subnet =>")
net_ips_maxlen = 16
net_ips_num_start_end = 3
for i, ip in enumerate(net_ips):
if len(net_ips) > net_ips_maxlen:
if i == net_ips_num_start_end:
print(" [...]")
if i > net_ips_num_start_end - 1 and i < len(net_ips) - net_ips_num_start_end:
continue
print(" - " + str(ip.ipv4()))
if __name__ == "__main__":
net_cidr = ""
if len(sys.argv) == 2:
if sys.argv[1][0] == "-":
# option
pass
else:
net_cidr = sys.argv[1]
if len(net_cidr) == 0:
try:
net_cidr = getNetwork()
except KeyboardInterrupt:
print("\nCtrl+C pressed -> aborting ...")
sys.exit(0)
main(net_cidr)