Why are sockets closed in list comprehension, but not for loop?

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?

+5
source share
1 answer

There are no links to your open sockets, which means they are garbage collected. Outlets are closed as soon as they are collected with garbage .

Exactly, when the sockets on your list understand garbage collection, they differ between Python implementations. CPython uses reference counting and therefore closes sockets as soon as the last link is dropped. Other implementations may delay closing until the next GC cycle.

+8
source

Source: https://habr.com/ru/post/1240361/


All Articles