Wrong open ports on the port scanner challenge

Tell us what’s happening:
The port-scanner program I wrote passes all but the last two tests, where it has to scan the hostname ‘scanme.nmap.org’ and it returns six more ports than the test (and the port 22 is missing).

Traceback (most recent call last):
  File "/home/runner/boilerplate-port-scanner/test_module.py", line 40, in test_port_scanner_verbose_hostname_multiple_ports
    self.assertEqual(actual, expected, "Expected 'Open ports for scanme.nmap.org (\nPORT     SERVICE\n22       ssh\n80       http'")
AssertionError: 'Open[57 chars]CE\n20       ftp\n21       ftp\n25       smtp\[70 chars]http' != 'Open[57 chars]CE\n22       ssh\n80       http'
  Open ports for scanme.nmap.org (
+ 22       ssh
- 20       ftp
- 21       ftp
- 25       smtp
- 43       whois
- 53       dns
- 67       dhcp
- 68       dhcp
  80       http : Expected 'Open ports for scanme.nmap.org (
22       ssh
80       http'

I cannot understand what is wrong with my code.

Your code so far

import socket
from common_ports import ports_and_services as pas
import re

def get_open_ports(target, port_range, verbose = False):
    port_range[1] += 1
      ip = socket.gethostbyname(target)
      if re.search('[a-zA-Z]', target):
        return "Error: Invalid hostname"
        return "Error: Invalid IP address"

    url = socket.getfqdn(ip)
    s = socket.socket()

    portS = 'Open ports for ' + url
    if url != ip:
      portS += ' (' + ip + ')'
    portS += '\nPORT     SERVICE'
    open_ports = []

    for port in range(*port_range):
      if s.connect_ex((ip, port)):
        service = pas.get(port, None)
        if service is not None:
          portS += '\n' + str(port).ljust(4) + '     ' + service

    if verbose is True:
      return portS
    return open_ports

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36

Challenge: Port Scanner

Link to the challenge:

According to the docs, socket.connect_ex() returns 0 on success, which means your conditional only matches on unsuccessful connections.

I also found it necessary to create a new socket, to attempt connection, and to close the socket each time to get things to work although I have a feeling there is a faster way.

Thanks a lot!
Since I was passing most of the tests, I didn’t think I’d made such a mistake.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.