Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query TCP socket connection state in Python

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.

like image 662
Michael Avatar asked Aug 12 '13 10:08

Michael


1 Answers

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.

like image 110
vahidne Avatar answered Oct 11 '22 05:10

vahidne