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.

     

    2 Responses to “Simple Socket Connection Test in Python 3”

    1. 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

    2. Thanks Patrick,
      Just fixed it and thanks for the feedback.

    Leave a Reply

    (required)

    (required)

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    © 2012 techniQal support Suffusion theme by Sayontan Sinha