A port of libnl, a collection of libraries providing APIs to the Netlink protocol based Linux kernel interfaces. This library is API-equivalent to the original C library, and should make it relatively easy to convert C programs into pure Python without having to call external binaries.
As Netlink is a Linux-specific protocol, this library will only work on Linux hosts. All communication is done using sockets between the Python process and the Linux kernel. The main driver for porting libnl was to use nl80211 in Python to scan for wireless access points natively, without having to run an external program and parse its output.
- Python 2.6, 2.7, PyPy, PyPy3, 3.3, and 3.4 supported on Linux.
Install:
pip install libnlA simple Python program that merely lists network adapters on the host:
importctypesimportsocketfromlibnl.errorimporterrmsgfromlibnl.handlersimportNL_CB_CUSTOM, NL_CB_VALID, NL_OKfromlibnl.linux_private.if_linkimportIFLA_IFNAME, IFLA_RTAfromlibnl.linux_private.netlinkimportNETLINK_ROUTE, NLMSG_LENGTH, NLM_F_DUMP, NLM_F_REQUESTfromlibnl.linux_private.rtnetlinkimportRTA_DATA, RTA_NEXT, RTA_OK, RTM_GETLINK, ifinfomsg, rtgenmsgfromlibnl.miscimportget_stringfromlibnl.msgimportnlmsg_data, nlmsg_hdrfromlibnl.nlimportnl_connect, nl_recvmsgs_default, nl_send_simplefromlibnl.socket_importnl_socket_alloc, nl_socket_modify_cbdefcallback(msg, _):
nlh=nlmsg_hdr(msg)
iface=ifinfomsg(nlmsg_data(nlh))
hdr=IFLA_RTA(iface)
remaining=ctypes.c_int(nlh.nlmsg_len-NLMSG_LENGTH(iface.SIZEOF))
whileRTA_OK(hdr, remaining):
ifhdr.rta_type==IFLA_IFNAME:
print('Found interface {0}: {1}'.format(iface.ifi_index, get_string(RTA_DATA(hdr)).decode('ascii')))
hdr=RTA_NEXT(hdr, remaining)
returnNL_OKsk=nl_socket_alloc() # Creates an nl_sock instance.ret=nl_connect(sk, NETLINK_ROUTE) # Create file descriptor and bind socket.ifret<0:
raiseRuntimeError('nl_connect() returned {0} ({1})'.format(ret, errmsg[abs(ret)]))
rt_hdr=rtgenmsg(rtgen_family=socket.AF_PACKET)
ret=nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST|NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF)
ifret<0:
raiseRuntimeError('nl_send_simple() returned {0} ({1})'.format(ret, errmsg[abs(ret)]))
nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, None) # Add callback to the nl_sock instance.ret=nl_recvmsgs_default(sk) # Get kernel's answer, and call attached callbacks.ifret<0:
raiseRuntimeError('nl_recvmsgs_default() returned {0} ({1})'.format(ret, errmsg[abs(ret)]))Here are some more examples with their C equivalents in order from "easy" to "hard":
- example_list_network_interfaces.py (list_network_interfaces.c)
- example_show_wifi_interface.py (show_wifi_interface.c)
- example_scan_access_points.py (scan_access_points.c)
This project adheres to Semantic Versioning.
- Added
- Python2.6, PyPy, and PyPy3 support.
- Initial release.