Search code examples
pythonsocketsports

Identifying listening ports using Python


In translating some scripts from bash, I am encountering many uses of netstat -an to find if one of our services is listening. While I know I can just use subprocess.call or other even popen I would rather use a pythonic solution so I am not leveraging the unix environment we are operating in.

From what I have read the socket module should have something but I haven't seen anything that checks for listening ports. It could be me not understanding a simple trick, but so far I know how to connect to a socket, and write something that lets me know when that connection failed. But not necessarily have I found something that specifically checks the port to see if its listening.

Any ideas?


Solution

  • How about trying to connect...

    import socket
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = s.connect_ex(('127.0.0.1', 3306))
    
    if result == 0:
        print('socket is open')
    s.close()