How do I reopen a socket after closing it?

Tell us what’s happening:
I close my socket with the following line in a for loop:

s.close()

But after closing it the socket is no longer useful for the rest of the for loop (for the rest of the for loop, connect_ex() returns the number 10038, which is code for:

Socket operation on nonsocket.

An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select , a member of an fd_set was not valid.

How do I close the socket and reopen it cleanly to scan the next port?

Thanks for your time

Jaime

Your code so far

import socket

def get_open_ports(target_URL, port_range):
    target_ip = socket.gethostbyname(target_URL)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(10)
    for i in range(port_range[0], port_range[1]+1, 1):
        connection_num = s.connect_ex((target_ip, i))
        if connection_num != 0:
            print(connection_num)
            print("The port is closed", i)
        else:
            print(connection_num)
            print("The port is open", i)
            s.close()
            print('closed')

# Verbose called with host name -- multiple ports returned
ports = get_open_ports("scanme.nmap.org", [20, 80])
print(ports + '\n')

Your browser information:

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

Challenge: Port Scanner

Link to the challenge:

1 Like

Figured it out

Just needed these two lines to be INSIDE of the for loop, not outside:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)

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