from flask import Blueprint, request, jsonify import ipaddress from util.logger import logger from auth.token import verify_token ipcalc_blueprint = Blueprint('ipcalc_tool', __name__) @ipcalc_blueprint.route('/api/ip/calculate', methods=['POST']) def ip_calculate(): user = verify_token() if not user: return jsonify({"message": "Nicht autorisiert"}), 401 try: data = request.get_json() or {} cidr = data.get("cidr", "").strip() try: network = ipaddress.IPv4Network(cidr, strict=False) except ValueError as e: return jsonify({"message": f"Ungültige CIDR-Notation: {e}"}), 400 hosts = list(network.hosts()) first_host = str(hosts[0]) if hosts else str(network.network_address) last_host = str(hosts[-1]) if hosts else str(network.broadcast_address) total_hosts = len(hosts) # Wildcard = inverse of netmask netmask_int = int(network.netmask) wildcard_int = (~netmask_int) & 0xFFFFFFFF wildcard = str(ipaddress.IPv4Address(wildcard_int)) ip_class = "Privat" if network.is_private else "Öffentlich" return jsonify({ "network": str(network.network_address), "broadcast": str(network.broadcast_address), "netmask": str(network.netmask), "wildcard": wildcard, "first_host": first_host, "last_host": last_host, "total_hosts": total_hosts, "prefix_length": network.prefixlen, "ip_class": ip_class, }) except Exception as e: logger.error(f"Fehler ipcalc: {e}") return jsonify({"message": "Fehler bei der Berechnung"}), 500