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:
- You can use an ip or hostname for the host variable value.
- You can test UDP sockets by changing socket.SOCK_STREAM to socket.SOCK_DGRAM.
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.