🛡️
Hello root
  • Sobre mi
  • Día 1 : Hardware y Software
  • Kali Linux y Virtualizacion
    • Virtualización
    • Cómo instalar Kali-Linux
    • Instalar Kali-linux en pendrive
  • Básicos de Linux
    • Usuarios y permisos en Linux. Primeros comandos
    • Challenge (reto_comandos)
    • Chuleta de comandos Linux
  • Programación (python)
    • Introducción a la programación
    • Python 1 | Variables, print() y funciones básicas
    • Python 2 | Listas y operadores
    • Python 3 | Bucles y funciones
    • Challenge (reto_python_server)
    • Python: Subnet and Host Capacity Calculator
  • Programación C#
    • Variables y condicionales
  • Bucles y colecciones
    • Ejercicio Bucles y colecciones
  • Métodos y funciones
    • Ejercicio math
  • C# Clases
  • Redes
    • Redes y topologías
    • Protocolos y tools
    • Comandos y servicios
  • Criptografía
    • Criptografia. Cifrado e Historia
  • Informes
    • T1043 - Exfiltración de Credenciales Mediante Protocolos de Red Inseguros
Powered by GitBook
On this page
  1. Programación (python)

Python: Subnet and Host Capacity Calculator

PreviousChallenge (reto_python_server)NextVariables y condicionales

Last updated 11 days ago

Puedes ver este scripte en

#!/usr/bin/env python3
import ipaddress
import sys

def analyze_network(ip_range, new_prefix=None):
    try:
        network = ipaddress.ip_network(ip_range, strict=False)
    except ValueError as e:
        print(f"Error: {e}")
        return

    print(f"\nOriginal Network: {network}")
    print(f"  Network Address: {network.network_address}")
    print(f"  Broadcast Address: {network.broadcast_address}")
    print(f"  Subnet Mask: /{network.prefixlen}")
    print(f"  Usable Hosts: {network.num_addresses - 2}")

    if new_prefix:
        new_prefix = int(new_prefix)
        if new_prefix > network.prefixlen:
            subnets = list(network.subnets(new_prefix=new_prefix))
            print(f"\nSubnets with /{new_prefix}: {len(subnets)}")
            print(f"  Hosts per Subnet: {subnets[0].num_addresses - 2}")
        else:
            print("\nWarning: New prefix must be larger than the original to create subnets.")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 ip_analyzer.py <ip_range> [new_prefix]")
        sys.exit(1)

    ip_range = sys.argv[1]
    new_prefix = sys.argv[2] if len(sys.argv) > 2 else None
    analyze_network(ip_range, new_prefix)

Explicación línea por línea de ip_analyzer.py

#!/usr/bin/env python3

Indica que el script debe ejecutarse con el intérprete de Python 3.

import ipaddress
import sys

Importa los módulos necesarios:

  • ipaddress para manipulación de redes IP.

  • sys para acceder a argumentos desde la línea de comandos.

def analyze_network(ip_range, new_prefix=None):

Define una función llamada analyze_network que recibe un rango IP y opcionalmente un nuevo prefijo de subred.

    try:
        network = ipaddress.ip_network(ip_range, strict=False)
    except ValueError as e:
        print(f"Error: {e}")
        return

Intenta crear una red a partir del rango IP ingresado. Si hay un error de formato, lo muestra y termina la función.

    print(f"\nOriginal Network: {network}")
    print(f"  Network Address: {network.network_address}")
    print(f"  Broadcast Address: {network.broadcast_address}")
    print(f"  Subnet Mask: /{network.prefixlen}")
    print(f"  Usable Hosts: {network.num_addresses - 2}")

Imprime la información principal de la red:

  • Red

  • Dirección de red

  • Dirección de broadcast

  • Máscara de subred

  • Cantidad de hosts usables (excluye dirección de red y broadcast)

    if new_prefix:
        new_prefix = int(new_prefix)
        if new_prefix > network.prefixlen:
            subnets = list(network.subnets(new_prefix=new_prefix))
            print(f"\nSubnets with /{new_prefix}: {len(subnets)}")
            print(f"  Hosts per Subnet: {subnets[0].num_addresses - 2}")
        else:
            print("\nWarning: New prefix must be larger than the original to create subnets.")

Si se proporciona un nuevo prefijo:

  • Lo convierte a entero.

  • Verifica que sea mayor que el prefijo original (para poder subdividir).

  • Calcula cuántas subredes se pueden generar y cuántos hosts tiene cada una.

  • Si el prefijo no es válido, muestra una advertencia.

if __name__ == "__main__":

Este bloque se ejecuta solo si el script se corre directamente (no si se importa como módulo).

    if len(sys.argv) < 2:
        print("Usage: python3 ip_analyzer.py <ip_range> [new_prefix]")
        sys.exit(1)

Verifica que al menos se haya pasado un argumento desde la consola. Si no, muestra un mensaje de uso y termina el programa.

    ip_range = sys.argv[1]
    new_prefix = sys.argv[2] if len(sys.argv) > 2 else None
    analyze_network(ip_range, new_prefix)

Toma los argumentos:

  • ip_range: primer argumento.

  • new_prefix: segundo argumento, si existe. Luego llama a la función analyze_network con esos valores.

Github