-
-
Save vndmtrx/dc412e4d8481053ddef85c678f3323a6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3 | |
# Use: ./subnet.py <ip/cidr> | |
# Alt: ./subnet.py <ip> <mask> | |
import sys | |
if __name__=="__main__": | |
addr = [0, 0, 0, 0] | |
mask = [0, 0, 0, 0] | |
cidr = 0 | |
if len(sys.argv) == 2: | |
(addr, cidr) = sys.argv[1].split('/') | |
addr = [int(x) for x in addr.split(".")] | |
cidr = int(cidr) | |
mask = [( ((1<<32)-1) << (32-cidr) >> i ) & 255 for i in reversed(range(0, 32, 8))] | |
elif len(sys.argv) == 3: | |
addr = sys.argv[1] | |
mask = sys.argv[2] | |
addr = [int(x) for x in addr.split(".")] | |
mask = [int(x) for x in mask.split(".")] | |
cidr = sum((bin(x).count('1') for x in mask)) | |
else: | |
print("Use: {0} <ip/cidr>".format(sys.argv[0])) | |
print("Alt: {0} <ip> <mask>".format(sys.argv[0])) | |
sys.exit(-1) | |
netw = [addr[i] & mask[i] for i in range(4)] | |
bcas = [(addr[i] & mask[i]) | (255^mask[i]) for i in range(4)] | |
print("Address: {0}".format('.'.join(map(str, addr)))) | |
print("Mask: {0}".format('.'.join(map(str, mask)))) | |
print("Cidr: {0}".format(cidr)) | |
print("Network: {0}".format('.'.join(map(str, netw)))) | |
print("Broadcast: {0}".format('.'.join(map(str, bcas)))) |
Tried creating a all in one IPv4 Subnet Calculator where in you can enter any kind of arguments.
Give it a try...Thanks
import ipaddress
IP_Addr = ipaddress.ip_interface(input('Enter IP address in IP/Mask Form : '))
Net_Addr = IP_Addr.network
pref_len = IP_Addr.with_prefixlen
Mask = IP_Addr.with_netmask
wildcard = IP_Addr.hostmask
broadcast_address = Net_Addr.broadcast_address
print('Network Address : ', str(Net_Addr).split('/')[0])
print('Broadcast Address : ' , broadcast_address)
print('CIDR Notation : ', pref_len.split('/')[1])
print('Subnet Mask : ', Mask.split('/')[1])
print('Wildcard Mask : ' , wildcard)
print('First IP : ' , list(Net_Addr.hosts())[0])
print('Last IP : ' , list(Net_Addr.hosts())[-1])
Thanks for this code, I used it here for creating a CIDR -> Netmask map when parsing Azure IPs and converting them into subnet masks needed by Cisco: https://gist.github.com/plambrechtsen/ca0a08d947c7f5dac6ed85805616105b
Great tip folks thanks, I wanted just hosts for a subnet so i used: