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 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
Enrich IP addresses with metadata and security IoC

Stratosphere IP enrich Get an IP address and enrich it with metadata and IoC You need API keys for VirusTotal and PassiveTotal (RiskIQ) How to use fro

Stratosphere IPS 10 Sep 25, 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
A simple chat room using socket and threading for handle multiple connections.

• Socket Chat Room was a little project for socket study. It works with a server handling the incoming connections from the clients. Clients send encoded messages while waiting for others clients mes

Guilherme de Oliveira 2 Mar 03, 2022
tradingview socket api for fetching real time prices.

tradingView-API tradingview socket api for fetching real time prices. How to run git clone https://github.com/mohamadkhalaj/tradingView-API.git cd tra

MohammadKhalaj 35 Dec 31, 2022
KoreaVPN - Create a VPN App for Mac Using Automator

VPN app 만들기 (a.k.a. KoreaVPN) VPN을 사용하기 위해 들어가는 10초의 시간을 아끼고, 귀찮음을 최소화 하기 위해 크롤링

DongHee 6 Jan 17, 2022
stellar-add-guest is a small tool to generate a new guest for Stellar Wireless (Enterprise mode) in OmniVista 2500 hosted on OmniSwitch with AOS Release 8

stellar-add-guest is a small tool to generate a new guest for Stellar Wireless (Enterprise mode) in OmniVista 2500 hosted on OmniSwitch with AOS Release 8.

BennyE 3 Jan 24, 2022
Tiny JSON RPC via HTTP library.

jrpc Simplest ever possible Asynchronous JSON RPC via HTTP library for Python, backed by httpx. Installation pip install async-jrpc Usage Import JRPC

Onigiri Team 2 Jan 31, 2022
Openconnect VPN RPi Gateway

Openconnect-VPN-RPi-Gateway See the blog (Chinese) for how to build an Openconne

Zhongze Tang 2 Jan 30, 2022
A simple, personal chat program that runs on a single computer. No Internet, just you.

MultiChat A simple, personal chat program that runs on a single computer. No Internet, just you. Simple and Local MultiChat was created with ease of u

Owls 2 Aug 19, 2022
A simple, configurable application and set of services to monitor multiple raspberry pi's on a network.

rpi-info-monitor A simple, configurable application and set of services to monitor multiple raspberry pi's on a network. It can be used in a terminal

Kevin Kirchhoff 11 May 22, 2022
This tool extracts Credit card numbers, NTLM(DCE-RPC, HTTP, SQL, LDAP, etc), Kerberos (AS-REQ Pre-Auth etype 23), HTTP Basic, SNMP, POP, SMTP, FTP, IMAP, etc from a pcap file or from a live interface.

This tool extracts Credit card numbers, NTLM(DCE-RPC, HTTP, SQL, LDAP, etc), Kerberos (AS-REQ Pre-Auth etype 23), HTTP Basic, SNMP, POP, SMTP, FTP, IMAP, etc from a pcap file or from a live interface

1.6k Jan 01, 2023
Library containing the core modules for the kingdom-python-server.

🏰 Kingdom Core Library containing the core modules for the kingdom-python-server. Installation Use the package manager pip to install kingdom-core. p

T10 4 Dec 27, 2021
openPortScanner is a port scanner made with Python!

Port Scanner made with python • Installation • Usage • Commands Installation Run this to install: $ git clone https://github.com/Miguel-Galdin0/openPo

Miguel Galdino 7 Jan 09, 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.

84 Jan 01, 2023
Tool written on Python that locate all up host on your subnet

HOSTSCAN Easy to use command line network host scanner. From noob to noobs. Dependencies Nmap 7.92 or superior Python 3.9 or superior All requirements

NexCreep 4 Feb 27, 2022
Wifi-Jamming is a simple, yet highly effective method of causing a DoS on a wireless implemented using python pyqt5.

pyqt5-linux-wifi-jamming-tool Linux-Wifi-Jamming is a simple GUI tool, yet highly effective method of causing a DoS on a wireless implemented using py

lafesa 8 Dec 05, 2022
NSX-T infrastructure as code - SDDC deployment

Deploy NSX-T Infrastructure - Simple Topology by Nicolas MICHEL @vpackets / LinkedIn Introduction The purpose of this entire repository is to automate

21 Nov 28, 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
A website to list Shadowsocks proxies and check them periodically

Shadowmere An automatically tested list of Shadowsocks proxies. Motivation Collecting proxies around the internet is fun, but what if they stop workin

Jorge Alberto Díaz Orozco (Akiel) 29 Dec 21, 2022