Q:

Is there a way to list all the sockets in use from Python?

I'm trying to open a telnet session between a Linux machine and some equipment using using telnetlib. The problem is that sometimes it happens that the socket might be taken by a different session and I would like to know:

if there is a way to list the sockets in use? how to list them?
what application is using the socket
how to close(free) a specific socket.

I've looked around but couldn't not find anything clear.
Cheers,
I.

A:

From the command line I would do tasks 1 & 2 by calling netstat and piping the result into grep to filter.  
netstat -an | grep "pid of script"

If you need to do this from a Python script you should be able to call netstate from a subprocess and catch the output and exit code. From there you can use regex filter the output. Not sure how to close the socket with Python though, as you may need root privileges. 

