pythonsocketsnetlink

Python3: how can we close netlink socket blocking recv?


I have the raw socket in Python as below to receive netlink messages from linux kernel.

socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, socket.NETLINK_ROUTE)

I am doing blocking recv on this socket and want to close it from another Python thread. However, calling shutdown(socket.SHUT_RD) on this socket returns an error ([Errno95] Operation not supported)

Why is that? How can we close this socket? I am using Python 3.7

There is no mention of this behavior in https://docs.python.org/3/library/socket.html#socket

It states below:

Note close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close().


Solution

  • If you want to close the connection in a timely fashion, call shutdown() before close()

    This statement is about connected sockets. TCP sockets are connected, but UDP, Raw, Netlink sockets etc are not. That's why shutdown is not supported on such sockets. Use a simple close instead.