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 script for generating WireGuard configs from Surfshark VPN

Surfshark WireGuard A script for generating WireGuard configs from Surfshark VPN. You must have python3 available on your machine. Usage Currently we

Alireza Ahmand 58 Dec 23, 2022
Wifi-jammer - Continuously perform deauthentication attacks on all detectable stations

wifi-jammer Continuously perform deauthentication attacks on all detectable stat

Leonardo de Araujo 14 Nov 03, 2022
Simple Port Scanner script written in Python, plans is to expand upon this script to turn it into a GUI based pen testing suite

PortScanner Simple Port Scanner script written in Python, plans is to expand upon this script to turn it into a GUI based pen testing suite. #IMPORTAN

1 Oct 23, 2021
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
EV: IDS Evasion via Packet Manipulation

EV: IDS Evasion via TCP/IP Packet Manipulation 中文文档 Introduction EV is a tool that allows you crafting TCP packets and leveraging some well-known TCP/

256 Dec 08, 2022
This is a python based command line Network Scanner utility, which input as an argument for the exact IP address or the relative IP Address range you wish to do the Network Scan for and returns all the available IP addresses with their MAC addresses on your current Network.

This is a python based command line Network Scanner utility, which input as an argument for the exact IP address or the relative IP Address range you wish to do the Network Scan for and returns all t

Abhinandan Khurana 1 Feb 09, 2022
It can be used both locally and remotely (indicating IP and port)

It can be used both locally and remotely (indicating IP and port). It automatically finds the offset to the Instruction Pointer stored in the stack.

DiegoAltF4 13 Dec 29, 2022
Some files casually made by @AneekBiswas

Python-Tools All Pyhthon Files are created and managed by @AneekBiswas Modules needed to be downloaded 1.CLI bagels.py random guess.py random text-tow

1 Feb 23, 2022
WARP+ uses Cloudflare’s virtual private backbone, known as Argo, to achieve higher speeds and ensure your connection is encrypted across the long haul of the Internet

WARP+ uses Cloudflare’s virtual private backbone, known as Argo, to achieve higher speeds and ensure your connection is encrypted across the long haul of the Internet

Rivane Rasetiansyah 3 Apr 01, 2022
GhostVPN - Simple and lightweight TUI application for CyberGhostVPN

GhostVPN Simple and lightweight TUI application for CyberGhostVPN. Screenshot Us

Mehmet Ali KERİMOĞLU 5 Jul 27, 2022
MQTT Explorer - MQTT Subscriber client to explore topic hierarchies

mqtt-explorer MQTT Explorer - MQTT Subscriber client to explore topic hierarchies Overview The MQTT Explorer subscriber client is designed to explore

Gambit Communications, Inc. 4 Jun 19, 2022
🌐 Tools for Networking

🌐 Network Tools Tools for Networking This repository contains the tools needed to make networking easier. Make sure to download all of the requiremen

Tornaido 1 Jan 15, 2022
Desktop application for checking sites connection in a background mode

Site connectivity checker Desktop application for checking site connection in a background mode by sending ICMP messages. Problem and solution Usually

Karina Singatullina 26 Dec 19, 2022
Malcolm is a powerful, easily deployable network traffic analysis tool suite for full packet capture artifacts (PCAP files) and Zeek logs.

Malcolm is a powerful, easily deployable network traffic analysis tool suite for full packet capture artifacts (PCAP files) and Zeek logs.

Cybersecurity and Infrastructure Security Agency 1.3k Jan 08, 2023
This Python script can be used to bypass IP source restrictions using HTTP headers.

ipsourcebypass This Python script can be used to bypass IP source restrictions using HTTP headers. Features 17 HTTP headers. Multithreading. JSON expo

Podalirius 322 Dec 28, 2022
forward several ports into a single port

port forwarding Multi-Input-Single-Output forward several ports into a single one this tool forwards packets from several ports into one single port.

Erfan Kheyrollahi Qaroğlu 3 Sep 11, 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

1 Nov 29, 2021
Remote vanilla PDB (over TCP sockets) done right: no extras, proper handling around connection failures and CI.

Overview docs tests package Remote vanilla PDB (over TCP sockets) done right: no extras, proper handling around connection failures and CI. Based on p

Ionel Cristian Mărieș 227 Dec 27, 2022
These scripts send notifications to a Webex space when a new IP is banned by Expressway, and allow to request more info or change the ban status

Spam Call and Toll Fraud Mitigation Cisco Expressway release X14 is able to mitigate spam calls and toll fraud attempts by jailing the spam IP address

Luca Pellegrini 6 Aug 05, 2022
Tool to get the top 100 of the fastest nodes in the Tor network. Based on Kirzahk tool.

Tor Network Top 100 IPs Tool to get the top 100 of the fastest nodes in the Tor network. Based on Kirzahk tool. Just execute top100ipstor.py to get th

Juan Manuel 0 Jan 23, 2022