Port-Scanner || socket.herror: [Errno 1] Unknown host

Hello I have trouble with my Port-Scanner project and hope that someone could help me out.
My code should work fine and the program runs on my PC in VSCode but if I copy the code to repl.it I get an error:

Traceback (most recent call last):
File “main.py”, line 10, in
ports = port_scanner.get_open_ports(“104.26.10.78”, [8079, 8090])
File “/home/runner/boilerplate-port-scanner-1/port_scanner.py”, line 26, in get_open_ports
sam= socket.gethostbyaddr(target)[0]+ ’ (’ + target + ‘)’
socket.herror: [Errno 1] Unknown host

This is my code so far:

import socket
from common_ports import ports_and_services

def get_open_ports(target, port_range, verbose=True):
    open_ports = []
    i = 0
    if target[0].isdigit():
        ip = True
    else:
        ip = False
    try:
        for i in range((port_range[1]-port_range[0])+1):
            port = port_range[0] + i
            portchecker = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
            portchecker.settimeout(0.25)
            result = portchecker.connect_ex((target,port))
            if result == 0:
                open_ports.append(port)
                i+=1

        portchecker.close()
        
        if ip == False:
            sam = target + ' (' + str(socket.gethostbyname(target)) + ')'
        else:
            sam= socket.gethostbyaddr(target)[0]+ ' (' + target + ')'
        if verbose == True:
            copen_portsc = 'Open ports for ' + sam +  '\n' + 'PORT     SERVICE'
            for i in range(len(open_ports)):
                copen_portsc += '\n' + str(open_ports[i]) + (9-len(str(open_ports[i])))*' ' + ports_and_services[open_ports[i]]
            open_ports = copen_portsc
        print(open_ports)
        return(open_ports)
    except socket.gaierror:
        if ip == True:
            return('Error: Invalid IP address')
        else:
            return('Error: Invalid hostname')
    

This exception is thrown when there is a problem with gethostbyname_ex() and gethostbyaddr(). I believe in these tests, this exception will get thrown on the tests that have valid IP addresses and no hostnames. You can catch the exception and possibly print more details or you could use it as a signal for a good IP with no hostname.

I ran your code locally and could not get to that error though, as I was getting

ResourceWarning: Enable tracemalloc to get the object allocation traceback
/home/gray/src/work/fcc-isp-port-scanner/port_scanner.py:108: ResourceWarning: unclosed <socket.socket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.1.78', 60772), raddr=('45.33.32.156', 22)>

because portchecker.close() was not being executed in the previous loop and it looks like it was catching on all the open ports.

Good luck.