Reputation: 7726
When I'm opening a network connection in Python like
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.heise.de', 80))
I can read the connection state from the console:
netstat --all --program|grep <PID>
tcp 0 0 10.10.10.6:39328 www.heise.de:http VERBUNDEN 23829/python
But how can I read this connection state, CONNECTED, CLOSE_WAIT, ... from within Python? Reading through the socket documentation didn't give me any hint on that.
Upvotes: 9
Views: 9681
Reputation: 173
I've just duct-taped together half of a solution for this problem in case Google brings anyone else here.
import urllib2
import psutil
page = urllib2.urlopen(URL) # dummy URL
sock = page.fp # The socket object that's being held open
fileno = sock.fileno()
proc = psutil.Process()
connections = proc.connections()
matches = [x for x in connections if x.fd == fileno]
if not matches:
status = None
else:
assert len(matches) == 1
match = matches[0]
status = match.status
What to do once this socket is identified is still TBD.
Upvotes: 1
Reputation: 132
This is only for Linux:
You need getsockopt call. level is "IPPROTO_TCP" and option is "TCP_INFO", as suggested by tcp manual. It is going to return the tcp_info data as defined here where you can also find the enumeration for STATE values.
you can try this sample:
import socket
import struct
def getTCPInfo(s):
fmt = "B"*7+"I"*21
x = struct.unpack(fmt, s.getsockopt(socket.IPPROTO_TCP, socket.TCP_INFO, 92))
print x
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
getTCPInfo(s)
s.connect(('www.google.com', 80))
getTCPInfo(s)
s.send("hi\n\n")
getTCPInfo(s)
s.recv(1024)
getTCPInfo(s)
what you are looking for is the First item (integer) in the printed tuple. You can cross check the result with the tcp_info definition.
Note: size of tcp_info should be 104 but i got it working with 92, not sure what happened but it worked for me.
Upvotes: 12
Reputation: 48315
On Linux, you can use the TCP_INFO
option of getsockopt(2)
to learn the state of the connection.
Upvotes: 0