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

Owner
Diego Guedes
Diego Guedes
A tool which is capable of scanning ports as TCP & UDP and detecting open and closed ones.

PortScanner Scan All Open Ports Of The Target IP. A tool which is capable of scanning ports as TCP & UDP and detecting open and closed ones. Clone fro

Msf Nmt 17 Nov 26, 2022
Use Raspberry Pi and CircuitSetup's power monitor hardware to publish electrical usage to MQTT

This repo has code and notes for whole home electrical power monitoring using a Raspberry Pi and CircuitSetup modules. Beyond just collecting data, it

Eric Tsai 10 Jul 25, 2022
GlokyPortScannar is a really fast tool to scan TCP ports implemented in Python.

GlokyPortScannar is a really fast tool to scan TCP ports implemented in Python. Installation: This program requires Python 3.9. Linux

gl0ky 5 Jun 25, 2022
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
Serves some data over HTTP, once. Based on the built-in Python module http.server

serve-me-once Serves some data over HTTP, once. Based on the built-in Python module http.server.

Peder Bergebakken Sundt 2 Jan 06, 2022
Easy-to-use sync library for handy proxy parse

Proxy Parser About Synchronous library, for convenient and fast parsing of proxies from different sources. Uses Scrapy as a parser. At the moment the

Michael Mironov 2 Nov 22, 2022
Real-time text-editor using python tcp socket

Real-time text-editor using python tcp socket This project does not need any external libraries so you don't need to use virtual environments. All you

MatiYo 3 Aug 05, 2022
Learn how modern web applications and microservice architecture work as you complete a creative assignment

Micro-service Создание микросервиса Цель работы Познакомиться с механизмом работы современных веб-приложений и микросервисной архитектуры в процессе в

Григорий Верховский 1 Dec 19, 2021
a decompilation of NAP36 the widevine removal software for amz and nf used by p2p groups until it stoped working due to it using expired cdm keys

NAP36 a decompilation of NAP36 the widevine removal software for amz and nf used by p2p groups until it stoped working due to it useing expired cdm ke

9 Aug 29, 2021
Public HTTPS access to Home Assistant with Dataplicity service

Custom component for public HTTPS access to Home Assistant with Dataplicity service. Should work on any Linux PC or ARM, not only Raspberry as Dataplicity service said. Don't work on Windows.

Alex X 70 Oct 03, 2022
Building a Robust IOT device which is customizable, encrypted, secure and user friendly

Building a Robust IOT device which is customizable, encrypted, secure and user friendly, which uses a single GPIO pin to extract multiple sensor values

1 Jan 03, 2022
This is the code repository for Mastering Python for Networking and Security – Second Edition

Mastering Python for Networking and Security – Second Edition This is the code repository for Mastering Python for Networking and Security – Second Ed

Frank Gottinger 1 Feb 09, 2022
Discord RPC Generator With Python

Discord-RPC-Generator Thank you for using this Discord Custom RP Generator. This is 100% safe and open source. Download Discord for your computer here

1 Nov 09, 2021
Pteronode - Script for managing Pterodactyl nodes

pteronode Script for managing Pterodactyl nodes Pteronode allows you to create s

9 Sep 28, 2022
Data Exfiltration without ever making a connection. Using TCP header space.

TCPwned PoC toy code to exfiltrate data without ever making a TCP connection. This will never show up in firewall logs, much less, actually be monitor

2 Nov 21, 2022
Ip-Tracker: a script written in python for tracking Someone using targets ip-Tracker address

🔰 𝕀𝕡-𝕋𝕣𝕒𝕔𝕜𝕖𝕣 🔰 Ip-Tracker is a script written in python for tracking Someone using targets ip-Tracker address It was made by Spider Anongre

Spider Anongreyhat 15 Dec 02, 2022
Pesquise, filtre e obtenha informações sobre animes. ( Módulo PIP )

Pesquise, filtre e obtenha informações sobre animes. ( Módulo PIP )

AimCaffe 3 Jan 30, 2022
InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state.

🧞 InfraGenie InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state. T

Digger 53 Nov 23, 2022
Network-Shredder is a python based NIDS.

Network-Shredder is a python based NIDS.

Oussama RAHALI 9 Dec 13, 2022
Monitoring plugin to check network interfaces with Icinga, Nagios and other compatible monitoring solutions

check_network_interface - Monitor network interfaces This is a monitoring plugin for Icinga, Nagios and other compatible monitoring solutions to check

DinoTools 3 Nov 15, 2022