0

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().

leopoodle
  • 2,110
  • 7
  • 24
  • 36

1 Answers1

1

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.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • Thanks for the explanations! What I actually want to do is to unblock `recv()` so that I can close the thread in which `recv()` is running. Calling `close()` does not seem unblock `recv()`. Is that expected? – leopoodle Jan 09 '21 at 01:57
  • @leopoodle: based on "things found on the internet" like [this one](https://github.com/mdlayher/netlink/issues/92) it looks like a `close` in one thread might not wake up the `recv` in the other. Better use non-blocking sockets in combination with `select` or `poll`. – Steffen Ullrich Jan 09 '21 at 09:12