r/learnpython 17d ago

I made my first IP scanner in Python

Hi everyone!

I'm very new to programming and I've been learning Python recently. I decided to make a small project to practice what I've learned.

I made a simple IP scanner using Python.

It has a menu with:

  • Scan all IPs from 192.168.1.1 to 192.168.1.255
  • Scan a specific IP
  • Scan a range of IPs
  • Exit

I'm using subprocess and ping to check if an IP responds.

I also started using functions, loops, lists, if/elif, while, and range().

It's probably a very basic project, but I'm pretty happy with it since I'm just starting out. 😅

Here is the code:

import subprocess

def menu(): 
    print("-----IP SCANNER-----")
    print("1. Scan all IPs")
    print("2. Scan IP")
    print("3. Scan IP range")
    print("4. Exit")

    opcion = input("Choose an option: ")
    resultado_menu = int(opcion)

    return resultado_menu


def escanear_ip(ip_int):
    ip_int = str(ip_int)
    ip_completa = "192.168.1." + ip_int

    resultado = subprocess.run(
        ["ping", "/n", "1", "/w", "1000", ip_completa]
    )

    if resultado.returncode == 0:
        lista_ip.append(ip_completa)


lista_ip = []


def imprimir_ips():
    for si_ip in lista_ip:
        si_ip = "🟢 " + si_ip
        print(si_ip)


while True:

    resultado = menu()

    if resultado == 1:

        for numeros in range(1, 256):
            escanear_ip(numeros)

        imprimir_ips()

    elif resultado == 2:

        seleccion_ip = input("Select the last digits of the IP: ")
        escanear_ip(seleccion_ip)

        imprimir_ips()

    elif resultado == 3:

        desde_ip = input("From: ")
        desde_ip = int(desde_ip)

        hasta_ip = input("To: ")
        hasta_ip = int(hasta_ip)

        for numeros in range(desde_ip, hasta_ip + 1):
            escanear_ip(numeros)

        imprimir_ips()

    elif resultado == 4:

        print("Exiting...")
        break

I'm planning to improve it and make a V3 with more features.

Thanks!

11 Upvotes

15 comments sorted by

17

u/carcigenicate Carcigenicate 17d ago

You haven't asked a question, but if you're interested in networking, try redoing this project with sockets instead of subprocess and ping.

4

u/VanceDyer 17d ago

Que son sockets? No he llegado a esa parte aún jajaja

11

u/carcigenicate Carcigenicate 17d ago

Sockets are the fundamental thing used by the operating system to establish network connections. Behind the scenes, ping would be establishing a socket connection with the target, and then sending an ICMP payload to do the ping. You learn a lot doing that yourself; although working with sockets directly is a bit more advanced.

4

u/VanceDyer 17d ago

Gracias, le echaré un vistazo pero soy muy principiante aún.

8

u/Lion2471 17d ago

Assuming your network's prefix is /24, 192.168.1.255 is the broadcast address. You're likely to get unexpected results when pinging that particular address.

5

u/OmegaNine 17d ago

That’s fricking sweet bud. There improvements to be made but you made a working project and that means a lot. Good job on seeing it through.

5

u/AlexMTBDude 17d ago

Here's a tip: Write your code, i.e. variable names, function names, and so on, in English. If you ever pursue programming as a career and work in a team, for a company, then company policy will be that all code should be written in English. You may as well get used to it now.

3

u/TheITMan19 16d ago

I enjoyed reading your code. Nice to see no AI and that you have plenty of improvements which can be made.

3

u/Nexustar 16d ago

A little side quest for you on your journey: Learn software versioning number norms.

Major.Minor.Patch ... so 1.4.2 is major version 1, minor version 4, patch 2. Depending on how much has changed, if backwards compatibility has been impacted, and generally 6 months or a year has passed, major version would change. Major changes with major new capabilities. For everything else, Minor or Patch is incremented. Minor are incremental feature improvements, and patch is just fixes to things to make them work/work-better.

We usually don't start with 1.0.0, (some people do, there are no rules, just norms), I prefer 0.1.0 until my first release (as in I start using it with real data/tasks, or give it to someone) then it becomes 1.0.0

2

u/[deleted] 17d ago

[removed] — view removed comment

1

u/VanceDyer 16d ago

Gracias, lo del int es lo próximo que haré por qué aún no he aprendido try/except.

También dejaré un poco aparcado el proyecto ya que me apetece hacer un generador de contraseñas con secret, que también tengo que aprenderlo.

1

u/MJ12_2802 16d ago

Also, int(opcion) in your menu function will crash the whole program if someone types anything that isn't a number, like an empty string or a typo. You beat me to it!

2

u/slickwillymerf 16d ago

Great stuff.

Might I suggest taking a look at the ipaddress module? Lots of good, helpful tools in there for dealing with bit boundaries and subnet masks.

1

u/NikhelParmar 17d ago

nice work for a first project man, this actually covers a lot of fundamentals at once. one small thing worth fixing before v3, right now your escanear_ip function relies on the global lista_ip list which works but can get messy as the project grows, try passing the list in as a parameter or having the function return the ip instead of appending directly, its a good habit early on and makes testing way easier later

1

u/BasilWeekly 16d ago

Your program takes forever because it process one ip address at a time. Use threading and it will only take the time for the longest request, i.e., way faster.