IPV4 network calculation project in Python

Overview

Curso de Python 3 do Básico ao Avançado

Desafio: Calculando redes IPV4

Criar um programa que obtem um numero de IP com o prefixo da mascara de rede.

O sistema irá calcular:

  • O IP da mascara de Rede
  • Primeiro IP
  • Ultimo IP
  • Total de hosts
  • IP e Mascara de rede convertidos em Binários

Solução:

Abaixo as funções vão receber a entrada de informção, a função validanumero tira os "." e '/" tornando uma lista com 5 itens, verificando se cada item não passa de 3 caracteres.

A função numero_ip converte cada membro da lista gerada em numero inteiro e verifica se o prefixo da mascara é valido.

from valida_ip import validanumero, numero_ip

print('Digite um endereço IP e o prefixo da mascara de rede:')
ip = input()
numero_ip(validanumero(ip))
from ipv4 import IPV4

def validanumero(valor):
    valor = valor.replace('/','.')
    valor = valor.split('.')
    for i in valor:
        if len(i) > 3:
            return
    return valor

def numero_ip(funcao):
    try:
        grupo1 = int(funcao[0])
        grupo2 = int(funcao[1])
        grupo3 = int(funcao[2])
        grupo4 = int(funcao[3])
        masc = int(funcao[4])

        if not masc <=32 or not masc >= 24:
            return print('Prefixo de máscara inválido')

        ipv4 = IPV4(grupo1, grupo2, grupo3, grupo4, masc)
        ipv4.lista_de_ip()
    except:
        print('Número de ip invalido')

Após a validação do numero IP é passado pelas funções converter_para_binario e binario_mascara_de_rede para a conversão do IP e mascara de rede em binário.
A função ip_mascara_de_rede gera uma nova mascara de rede e numerodehost gera o numero de Host que pode setar IP.

CALCULAR = [128, 64, 32, 16, 8, 4, 2, 1]

class IPV4:
    def __init__(self, grupo1, grupo2, grupo3, grupo4, mascarasubrede):
        self.grupo1 = grupo1
        self.grupo2 = grupo2
        self.grupo3 = grupo3
        self.grupo4 = grupo4
        self.mascarasubrede = mascarasubrede

    def converter_para_binario(self,valor):
        valor = bin(valor).zfill(8)
        valor = valor.replace('b','0')
        return valor

    def binario_mascara_de_rede(self):
        novamascara = ''
        valor = 8 - (32 - self.mascarasubrede)
        for i in range(valor):
            novamascara += '1'
        novamascara = '{:0<8}'.format(novamascara)
        return novamascara

    def ip_mascara_de_rede(self):
        ipmasc = 0
        for i in range(8):
            if self.binario_mascara_de_rede()[i] == '1':
                ipmasc += CALCULAR[i]
        return ipmasc

    def numerodehost(self):
        hosts = (2**(32 - self.mascarasubrede)) - 2
        return hosts

    def lista_de_ip(self):
        if not self.grupo4 > self.numerodehost():
            ip1 = self.converter_para_binario(self.grupo1)
            ip2 = self.converter_para_binario(self.grupo2)
            ip3 = self.converter_para_binario(self.grupo3)
            ip4 = self.converter_para_binario(self.grupo4)
            masc = self.binario_mascara_de_rede()
            print('#' * 56)
            print(f'# IP: {self.grupo1}.{self.grupo2}.{self.grupo3}.{self.grupo4}/{self.mascarasubrede}\n'
                f'# REDE: {self.grupo1}.{self.grupo2}.{self.grupo3}.0/{self.mascarasubrede}\n'
                f'# MÁSCARA: 255.255.255.{self.ip_mascara_de_rede()}\n'
                f'# PRIMEIRO IP: {self.grupo1}.{self.grupo2}.{self.grupo3}.1/{self.mascarasubrede}\n'
                f'# ÚLTIMO IP: {self.grupo1}.{self.grupo2}.{self.grupo3}.{self.numerodehost()}/{self.mascarasubrede}\n'
                f'# Nº DE IPs: {self.numerodehost()}')
            print('#' * 56)
            print(f'# Números em binários: \n'
                  f'# IP: {ip1}.{ip2}.{ip3}.{ip4}\n'
                  f'# Mascara de rede: 11111111.11111111.11111111.{masc}')
        else:
            print('Número de ip invalido')

Terminal:

imagem do terminal

You might also like...
Base on browser-time to get har from network, and use python to analyze the data .

base on browser-time to get har from network, and use python to analyze the data

DNSStager is an open-source project based on Python used to hide and transfer your payload using DNS.
DNSStager is an open-source project based on Python used to hide and transfer your payload using DNS.

What is DNSStager? DNSStager is an open-source project based on Python used to hide and transfer your payload using DNS. DNSStager will create a malic

School Project using Python Sockets and Personal Encryption Method.

Python-Secure-File-Transfer School Project using Python Sockets and Personal Encryption Method. Installation Must have python3 installed on your syste

Test - Python project for Collection Server and API Server

QProjectPython Collection Server 와 API Server 를 위한 Python 프로젝트 입니다. [FastAPI참고]

Terminal based chat - networking project with sockets in python
Terminal based chat - networking project with sockets in python

Terminal based chat - networking project with sockets in python

ANalyse is a vehicle network analysis and attack tool.
ANalyse is a vehicle network analysis and attack tool.

CANalyse is a tool built to analyze the log files to find out unique datasets automatically and able to connect to simple user interfaces suc

Flashes keyboard leds on incoming/outgoing network packets
Flashes keyboard leds on incoming/outgoing network packets

LED Net Capture Flashes keyboard leds on incoming/outgoing network packets Usage Requires root priviledges to run usage: ledcapture.py [-h] --keyboard

GNS3 Graphical Network Simulator

GNS3-gui GNS3 GUI repository.

Share clipboards between two devices in a network

Shared Clipboard I felt the need for sharing clipboard texts between virtual machines but I didn't find any reliable solutions for this (I use HyperV)

Owner
Diego Guedes
Diego Guedes
Nautobot is a Network Source of Truth and Network Automation Platform.

Nautobot is a Network Source of Truth and Network Automation Platform. Nautobot was initially developed as a fork of NetBox (v2.10.4). Nautobot runs as a web application atop the Django Python framework with a PostgreSQL database.

Nautobot 549 Dec 31, 2022
This Tool can help enginners and biggener in network, the tool help you to find of any ip with subnet mask that can calucate them and show you ( Availble IP's , Subnet Mask, Network-ID, Broadcast-ID )

This Tool can help enginners and biggener in network, the tool help you to find of any ip with subnet mask that can calucate them and show you ( Availble IP's , Subnet Mask, Network-ID, Broadcast-ID )

null 12 Dec 13, 2022
nettrace is a powerful tool to trace network packet and diagnose network problem inside kernel.

nettrace nettrace is is a powerful tool to trace network packet and diagnose network problem inside kernel on TencentOS. It make use of eBPF and BCC.

null 84 Jan 1, 2023
PcapXray - A Network Forensics Tool - To visualize a Packet Capture offline as a Network Diagram

PcapXray - A Network Forensics Tool - To visualize a Packet Capture offline as a Network Diagram including device identification, highlight important communication and file extraction

Srinivas P G 1.4k Dec 28, 2022
PcapConverter - A project for generating 15min frames out of a .pcap file containing network traffic

CMB Assignment 02 code + notebooks This is a project for containing code for the

Yannik S 2 Jan 24, 2022
Network-Shredder is a python based NIDS.

Network-Shredder is a python based NIDS.

Oussama RAHALI 9 Dec 13, 2022
this is demo of tool dosploit for test and dos in network with python

this tool for dos and pentest vul SKILLS: syn flood udp flood $ git clone https://github.com/amicheh/demo_dosploit/ $ cd demo_dosploit $ python3 -m pi

yaser amir chehrazi 5 Sep 22, 2022
Simple python script for automated network scans with random name generator(useful for CTF boxes).

?? Automated NMAP script Description Simple python script for automated network scans with random name generator(useful for CTF boxes). Requirements 1

Dhmos Funk 2 Oct 29, 2021
A Python framework for interacting with Solana's Pyth network.

Pyth Network A basic Python framework for reading and decoding data regarding the Pyth network

null 1 Nov 29, 2021
The can package provides controller area network support for Python developers

python-can The Controller Area Network is a bus standard designed to allow microcontrollers and devices to communicate with each other. It has priorit

Brian Thorne 904 Dec 29, 2022