create a basic network scanner in python

To create a basic network scanner in Python, we can use the socket library to ping a range of IP addresses. Here's an example code:

main.py
import socket

def scan_network(ip, port):
    # Create a TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(1) # Set timeout to 1 second

    try:
        # Connect to the IP and port
        sock.connect((ip, port))

        # Print open port
        print(f"IP address {ip} has port {port} open")
    except:
        pass # Fail silently if connection fails

    sock.close() # Close the socket

# Loop through a range of IP addresses and scan for an open port
for i in range(1, 255):
    ip = f"192.168.1.{i}"
    scan_network(ip, 80) # Scan port 80 (HTTP)
602 chars
23 lines

In this code, we define a scan_network function that takes an IP address and port number as input and attempts to connect to it using a TCP socket. If the connection is successful, the IP address and port number are printed to the console. We then loop through a range of IP addresses (in this case, assuming a 192.168.1.x network) and scan port 80 (the default HTTP port) for each one.

Note that this is a very basic example and there are many ways to improve it (e.g. by scanning multiple ports, handling errors more gracefully, etc.). In addition, some networks may have firewalls or other security measures in place that prevent scanning.

related categories

gistlibby LogSnag