This is not possible in Python.
The Linux kernel does not provide a mechanism in /procfs to report on TCP socket states (unlike BSD and other Unix-like OSs). As the kernel doesn't expose this info, we can't see it via the python-linux-procfs module or similar.
See lsof FAQ item 3.14.1:
Q. ‘Why doesn't lsof report socket options, socket states, and TCP flags and values for my dialect?’.
A. 'socket options, socket states, and TCP flags and values are not available via the /proc file system.'
However SystemTap's Network tapset provides a tcp.setsockopt breakpoint which can be used to intercept socket options set by a process, however this would be handled in stap rather than python.
I created the required tapset as follows:
# Show sockets setting options
# Return enabled or disabled based on value of optval
function getstatus(optlen)
{
if ( optlen == 1 )
return "enabling"
else
return "disabling"
}
probe begin
{
print ("\nChecking for apps making socket calls\n")
}
# See apps setting a socket option
probe tcp.setsockopt
{
status = getstatus(user_int($optval))
printf (" App '%s' (PID %d) is %s socket option %s... ", execname(), pid(), status, optstr)
}
# Check setting the socket option worked
probe tcp.setsockopt.return
{
if ( ret == 0 )
printf ("success")
else
printf ("failed")
printf ("\n")
}
probe end
{
print ("\nClosing down\n")
}