Skip to content

Instantly share code, notes, and snippets.

@RyanBreaker
Last active November 8, 2018 13:22
Show Gist options
  • Save RyanBreaker/915ce69cadd20a8f965f6832e6c60521 to your computer and use it in GitHub Desktop.
Save RyanBreaker/915ce69cadd20a8f965f6832e6c60521 to your computer and use it in GitHub Desktop.
Simple native Python 3 IP subnet calculator, no dependencies required. Inspired by http://jodies.de/ipcalc.
import sys, ipaddress
address = None
interactive = False
if len(sys.argv) > 1:
address = sys.argv[1]
else:
address = input('Network: ')
interactive = True
try:
address = ipaddress.IPv4Interface(address)
# Script doesn't support prefixes >31
if address.network.prefixlen >= 31:
raise ValueError
except ValueError:
print('Invalid input.', file=sys.stderr)
sys.exit(1)
network = address.network
output = f"""\
Address: {address.ip}
Netmask: {address.netmask}
Wildcard: {address.hostmask}
===========================
Network: {network}
Broadcast: {network.broadcast_address}
HostMin: {network[1]}
HostMax: {network.broadcast_address-1}
Hosts/Net: {network.num_addresses-2}\
"""
print(output)
if interactive:
input()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment