In the continuing vein of updating/refreshing my older python posts for Python 3, I have outlined the changes necessary to test for open TCP ports using Python 3. My original post showed you how to open a socket connection to a host:port to see if it was active and accepting connections. Luckily, this time around I didn’t have to change much of anything. Turns out the only missing links were my print statements. As I mentioned in my last post, Python3 has turned the print statement into a function. I also added some slightly better error handling to the example. If a connection fails, you can now see the cause of the failure.
Things to remember:
import socket
#Simply change the host and port values
host = '127.0.0.1'
port = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.shutdown(2)
print("Success connecting to ")
print(host," on port: ",str(port))
except socket.error as e:
print("Cannot connect to ")
print(host," on port: ",str(port))
print(e)
As always, I appreciate any feedback or modifications that would make this example more useful or easy to understand.
Thanks for posting this and your other Python posts…there’s a tiny typo in this post – there is no need for the second : after the ‘except socket.error as e:’ statement
Thanks Patrick,
Just fixed it and thanks for the feedback.