pymnl.nlsocket Module

pymnl.nlsocket.SOCKET_AUTOPID

Use this value as the pid parameter to Socket.bind() for automatic port ID selection.

pymnl.nlsocket.SOCKET_BUFFER_SIZE

The buffer size used when reading from and writing to the netlink socket. It is the smaller of 8 KiB or the system page size.

Socket level for netlink.

class pymnl.nlsocket.Socket(bus)

A netlink socket.

__init__(bus)
bus - the netlink socket bus ID
(see NETLINK_* constants in linux/netlink.h)

Raises an exception on error.

__weakref__

list of weak references to the object (if defined)

bind(pid=0, groups=0)

Bind netlink socket.

pid - The port ID you want to use. You can use
SOCKET_AUTOPID (which is 0) for automatic port ID selection.

groups - the group of message you're interested in

Raises an exception on error.

close()

Close the socket.

get_groups()

Obtain netlink groups from netlink socket.

get_portid()

Obtain netlink PortID from netlink socket.

This method returns the netlink PortID of this netlink socket. It's a common mistake to assume that this PortID equals the process ID which is not always true. This is the case if you open more than one socket that is binded to the same netlink subsystem from the same process.

get_sock()

Get the underlying socket object.

This is useful if you need to set non-netlink socket options.

getsockopt(optname, buflen=0)

Get a Netlink socket option.

optname - the option to get

buflen - optional (see Python's socket module)

recv(bufsize=4096, flags=0)

Receive a netlink message.

bufsize - max data to receive
Use SOCKET_BUFFER_SIZE (which is 8KB, see linux/netlink.h for more information). Using this buffer size ensures that your buffer is big enough to store the netlink message without truncating it.

flags - see socket.recv()

Raises an exception on error. Otherwise, it returns a MessageList.

send(nl_message)

Send a netlink message.

nl_message - the netlink message to be sent

Raises an exception on error. Otherwise, it returns the number of bytes sent.

setsockopt(optname, value)

Set Netlink socket option.

optname - option to set

value - value to set for the option

This method allows you to set some Netlink socket options. As of this writing (see linux/netlink.h), the existing options are:

  • NETLINK_ADD_MEMBERSHIP
  • NETLINK_DROP_MEMBERSHIP
  • NETLINK_PKTINFO
  • NETLINK_BROADCAST_ERROR
  • NETLINK_NO_ENOBUFS

In the early days, Netlink only supported 32 groups expressed in a 32-bits mask. However, since 2.6.14, Netlink may have up to 2^32 multicast groups but you have to use setsockopt() with NETLINK_ADD_MEMBERSHIP to join a given multicast group. This method internally calls setsockopt() to join a given netlink multicast group. You can still use Socket.bind() and the 32-bit mask to join a set of Netlink multicast groups.

See Python's socket module for more information about value.