I was following the instructions from this answer on how to check network ports in python: /a/19196218/8652920
for posterity I’ll just repost it
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print "Port is open"
else:
print "Port is not open"
sock.close()
This works but it only works once.
Python 3.12.5 (main, Aug 6 2024, 19:08:49) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> result = sock.connect_ex(('host', 22))
>>> result
0
>>> result = sock.connect_ex(('host', 22))
>>> result
56
see that we get the error code 56, which from this question [Errno 56]: Socket already connected fix? I can infer that it means the socket is already connected.
Now, I want to keep connecting and disconnecting to my host so that the result code is always 0. How do I do that?
sock.close
does not work by the way. see, continued:
>>> sock.close()
>>> result = sock.connect_ex(('host', 22))
>>> result
9
So, my question is how to keep trying the connection with connect_ex
repeatedly and get response code 0 each time. If the socket is already connected and stays connected after resolution of connect_ex
, then how do we disconnect?
2