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
API for concurrency connections

Multi-connection-server-API API for concurrency connections difference between this server and the echo server is the call to lsock.setblocking(False)

Muziwandile Nkomo 1 Jan 04, 2022
A working cloudflare uam bypass !!

Dark Utilities - Cloudflare Uam Bypass Our Website https://over-spam.space/ ! Additional Informations The proxies type are http,https ... You need fas

Inplex-sys 26 Dec 14, 2022
Automated network configuration backups using Github actions and git-scraping

Network Config Scraper This repository demonstrates the use of Github Actions and git-scraping to build an automated backup solution for network confi

WWT 19 Dec 14, 2022
A repository to spoof ARP table of any devices and successfully establish Man in the Middle(MITM) attack using Python3 in Linux

arp_spoofer A repository to spoof ARP table of any devices and successfully establish Man in the Middle(MITM) attack using Python3 in Linux Usage: git

Surya Das N 1 Oct 30, 2021
This application aims to read all wifi passwords and visualizes the complexity in graph formation by taking into account several criteria and help you generate new random passwords.

This application aims to read all wifi passwords and visualizes the complexity in graph formation by taking into account several criteria and help you generate new random passwords.

Njomza Rexhepi 0 May 29, 2022
Linux SBC featuring two wifi radios, masquerading as a USB charger.

The WiFiWart is an open source WiFi penetration device masquerading as a regular wall charger. It features a 1.2Ghz Cortex A7 MPU with two WiFi chips onboard.

Walker 151 Dec 26, 2022
Wallc - Calculate the layout on the wall to hang up pictures

wallc Calculate the layout on the wall to hang up pictures. Installation pip install git+https://github.com/trbznk/wallc.git Getting Started Currently

Alex Trbznk 68 Sep 09, 2022
👨🏼‍💻 ‎‎‎‏‏ A customizable man-in-the-middle TCP proxy with out-of-the-box support for HTTP & HTTPS.

👨‍💻 mitm A customizable man-in-the-middle TCP proxy with out-of-the-box support for HTTP & HTTPS. Installing pip install mitm Note that OpenSSL 1.1

Felipe 92 Jan 05, 2023
A simple implementation of an RPC toolkit

Simple RPC With Raw Sockets Repository for the Data network course project: Introduction In this project, you will attempt to code a simple implementa

Milad Samimifar 1 Mar 25, 2022
Simplest dashboard for WireGuard VPN written in Python w/ Flask

Hi! I'm planning the next major update for this project, please let me know if you have any suggestions or feature requests ;) You can create an issue

Donald Zou 763 Jan 02, 2023
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
A Python library to ease the integration with the Beem Africa (SMS, AIRTIME, OTP, 2WAY-SMS, BPAY, USSD)

python-client A Python library to easy the integration with the Beem Africa SMS Gateway Features to be Implemented Airtime OTP SMS Two way SMS USSD Bp

Beem Africa 24 Oct 29, 2022
A Project to resolve hostname and receive IP

hostname-resolver A Project to resolve hostname and receive IP Installation git clone https://github.com/ihapiw/hostname-resolver.git Head into the ho

iHapiW 5 Sep 12, 2022
Tool for pretty printing and optimizing Lightning Network channels.

Suez Tool for pretty printing and optimizing Lightning Network channels. Installation Install poetry poetry install poetry run ./suez Channel fee poli

Pavol Rusnak 69 Nov 03, 2022
A transport agnostic sync/async RPC library that focuses on exposing services with a well-defined API using popular protocols.

WARNING: This is from spyne's development branch. This version is not released yet! Latest stable release can be found in the 2_13 branch. If you like

1.1k Dec 23, 2022
CSP-style concurrency for Python

aiochan Aiochan is a library written to bring the wonderful idiom of CSP-style concurrency to python. The implementation is based on the battle-tested

Ziyang Hu 127 Dec 23, 2022
Simple threaded Python Rickroll server. Listens on port 23 by default.

Terminal Rickroll Simple threaded Python Rickroll server. Listens on port 23 by default. Rickroll video made using Video-To-Ascii and the standard ric

AG 10 Sep 13, 2022
Throttle rTorrent on Plex stream Start/Stop

Dependencies Python 3.6+ Tautulli Script Setup Edit rtorrent_throttle.py and set rTorrent username, password and RPC2 url. Tautulli Setup Commum Scrip

4 Apr 25, 2022
Multipurpose Growtopia Server tools, can be used for newbie to learn things.

Multipurpose Growtopia Server tools, can be used for newbie to learn things.

FelixF 3 Dec 01, 2021
AV Evasion, a Red Team Tool - Fiber, APC, PNG and UUID

AV Evasion, a Red Team Tool - Fiber, APC, PNG and UUID

9 Mar 07, 2022