I am trying to create a list of available ports in Python. I follow this tutorial , but instead of printing open ports, I add them to the list.
Initially, I had something like the following:
available_ports = [] try: for port in range(1,8081): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((remoteServerIP, port)) if result == 0: available_ports.append(port) sock.close() # ...
This works well, but it is well known that understanding is faster than loops , so now I have:
try: available_ports = [port for port in range(1, 8081) if not socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((remoteServerIP, port))]
I assumed that the sockets would not be closed, but I checked it with the following:
try: available_ports = [port for port in range(1, 8081) if not socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((remoteServerIP, port))] for port in range(1,8081): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((remoteServerIP, port)) if result == 0: print("Port {}: \t Open".format(port)) sock.close()
and indeed open ports were printed.
Why are sockets closed in understanding, but not in a for loop? Can I rely on this behavior or is it a red herring?