MrPat
MrPat

Reputation: 119

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

Upvotes: 1

Views: 2717

Answers (2)

SSutrave
SSutrave

Reputation: 56

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

Upvotes: 3

Alvaro Gutierrez Perez
Alvaro Gutierrez Perez

Reputation: 3887

There is not a standard way to know if a server has other opened connections before you attempt to connect to it. You must ask it either connecting to another service in the server that checks it, or by asking the other clients, if you know all of them.

That said, telnet servers should be able to handle more than one connection at a time, so it should not matter if there are more clients connected.

Upvotes: 1

Related Questions