Information Security Projects - Port Scanner

Tell us what’s happening:

My code gives the following error:

Traceback (most recent call last):
  File "/workspace/boilerplate-port-scanner/test_module.py", line 10, in test_port_scanner_ip
    self.assertEqual(actual, expected, 'Expected scanning ports of IP address to return [443].')
AssertionError: Lists differ: [] != [443]

Second list contains 1 additional elements.
First extra element 0:
443

- []
+ [443] : Expected scanning ports of IP address to return [443].

Your code so far

import socket
import ipaddress
from common_ports import ports_and_services

def get_open_ports(target, port_range, verbose = False):
    open_ports = []

    try:
        ipaddress.ip_address(target)
        is_ip = True
    except ValueError:
        is_ip = False

    try:
        if is_ip:
            ip = target
            try:
                hostname = socket.gethostbyaddr(ip)[0]
            except socket.herror:
                hostname = None
        else:
            hostname = target
            ip = socket.gethostbyname(target)

        for port in range(min(port_range), max(port_range) + 1):
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(1.0)
                result = s.connect_ex((ip, port))
                if result == 0:
                    open_ports.append(port)
        
        if verbose:
            display_name = hostname if hostname else ip
            if display_name != ip:
                out = f'Open ports for {display_name} ({ip})\nPORT     SERVICE'
            else:
                out = f'Open ports for {display_name}\nPORT     SERVICE'
            
            for port in open_ports:
                out += f'\n{str(port).ljust(9)}{ports_and_services[port]}'
            return out
        else:
            return open_ports
    except socket.gaierror:
        if is_ip or target.replace('.', '').isdigit():
            return 'Error: Invalid IP address'
        else:
            return 'Error: Invalid hostname'

Is there a mistake in the code or should I check for a port 443 specifically:

if result == 0 or port 443:
                    open_ports.append(port)

?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36

Challenge Information:

Information Security Projects - Port Scanner

There doesn’t seem to be anything clearly wrong. Maybe the ip is temporarily inaccessible.

1 Like

So, should I use (or port == 443) as an alternative for now - perhaps adding a comment for context - or should I wait for site’s ports to become available?