Search code examples
pythonwindowssocketsnetstatterminal-server

Check if socket is in use in python


I am running a script that telnets to a terminal server. Occasionally the script is launched while one instance is already running, which causes the already running script to fail with

EOFError: telnet connection closed

Is there a quick and easy and pythonic way to check if the required socket is already in use on the client computer before I try to open a connection with telnetlib?

SOLUTION:

I wanted to avoid making a subprocess call but since I do not control software on the client computers, and other programs may be using the same socket, the file lock suggestion below (a good idea) wouldn't work for me. I ended up using SSutrave's suggestion. Here is my working code that uses netstat in Windows 7:

# make sure the socket is not already in use
try:
    netstat = subprocess.Popen(['netstat','-nao'],stdout=subprocess.PIPE)
except:
    raise ValueError("couldn't launch netstat to check sockets. exiting")
ports = netstat.communicate()[0]
if (ip + ':' + port) in ports:
    print 'socket ' + ip + ':' + port + ' in use on this computer already. exiting'
    return

Solution

  • You can check for open ports by running the following linux command netstat | grep 'port number' | wc -l by importing subprocess library in python.