IPv4 Netzberechner
Zur Navigation springen
Zur Suche springen
Ein Python-Skript für die Berechnung der Netze von IPv4-Adressen.
Code
#!/bin/env python3
import math
import sys
def cidr2mask(cidr_nr):
"""Convert the CIDR notation to a subnet mask and return a string
representation of it.
"""
#Calculate full octetts
# octett = math.floor(cidr_nr / 8)
octett = math.ceil(cidr_nr / 8)
#Calculate exponent from CIDR notation
exp = (8 - (cidr_nr % 8)) % 8
#Fill octetts
mask = "0.0.0.0.0"
mask = mask.replace("0", "255", octett)
#Subtract 2 ** exponent from 256
m = 256 - (2 ** exp)
mask = mask.replace("0", str(m), 1)
return mask[4:]
def ip_table(ip, cidr):
"""Solves the subnetting problem as presented on
\"https://subnetipv4.com/\". Returns the answer as a dictionary.
"""
#calculate in which octett the network ID will change
octett = math.floor(cidr / 8)
#calculate the increment by which the networks IDs are found in
incr = 256 / (2 ** (cidr % 8))
#calculate the network ID and first usable ip adrress
net_id = ip.copy()
net_id[octett] = int(math.floor(net_id[octett] / incr) * incr)
for i in range(octett+1, 4):
net_id[i] = 0
first = net_id.copy()
first[-1] += 1
#calculate the ID of the next network
next_net = net_id.copy()
nx = next_net[octett] + incr
if nx == 256:
next_net[octett] = 0
next_net[octett-1] = next_net[octett-1] + 1
else:
next_net[octett] = nx
broadcast = net_id.copy()
broadcast[octett] += int(incr - 1)
broadcast[octett+1:] = [255 for i in broadcast[octett+1:]]
last = broadcast.copy()
last[-1] -= 1
fields = ["Net ID", "First IP", "Last IP", "Broadcast", "Next ID"]
return dict(zip(fields, [net_id, first, last, broadcast, next_net]))
if __name__ == '__main__':
ip_cidr = sys.argv[1]
# print(ip_cidr)
ip_cidr = ip_cidr.split("/")
ip = [int(i) for i in ip_cidr[0].split(".")]
cidr = int(ip_cidr[1])
ips = ip_table(ip, cidr)
print(".".join([str(i) for i in ips["Net ID"]]) + "/" + str(ip_cidr[1]))
# for i, j in ips.items():
# print(i, ":", j)
Installation
Skript kopieren und ausführbar machen:
xclip -sel clip -o > calcipv4net chmod +x calcipv4net
Benutzung
Komplette IPv4-Adresse als Argument angeben:
calcipv4net 10.28.38.48/18 #10.28.0.0/18