High-Level API

Examples

Changing the IP addresses of a network device

Note: This example requires effective UID 0 (“root”) or CAP_NET_ADMIN privileges to work.

First of all, let’s add a new IP address 2002:456:1::1/64 to the network interface wlan0 and grant it a lifetime of 60 seconds:

import netlink

network = netlink.Network()
device  = network.device('wlan0')
device.add_address('2002:4BC:1::1/64', valid_lft = 60, preferred_lft = 30)

Note: If you get an error similar to OSError: [Errno 19] No such device you’ll have to use the ip address show command to determine the name of a usable network device (such as eth0 or even lo) and use it instead of wlan0 in all example scripts.

Once we have successfully run the above code (either in an interactive Python shell or by copying it to a script file and running it), we can verify that the address was actually created using the ip address command:

$ ip address show dev wlan0
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    …
    inet6 2002:4BC:1::1/64 scope global dynamic 
       valid_lft 40sec preferred_lft 10sec
    …

The output might look a bit different for you and (if the device is currently used) there’ll probably be several other addresses shown next to the one we have just added.

You’ll also notice that the kernel already started counting down from the original 60 seconds we granted the address. I’d be a shame if our address were to disappears in less than 40 seconds, so let’s buy it some extra time using modify_address:

import netlink

network = netlink.Network()
device  = network.device('wlan0')
device.modify_address('2002:4BC:1::1/64', valid_lft = 2000, preferred_lft = 300)
$ ip address show dev wlan0
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    …
    inet6 2002:4BC:1::1/64 scope global dynamic 
       valid_lft 1990sec preferred_lft 290sec
    …

Excellent! Finally let’s get rid of this address after all and add a different one instead:

import netlink

network = netlink.Network()
device  = network.device('wlan0')
device.add_address('fe90::223:14ff:feb9:384/64', scope = 'Link', valid_lft = 30, preferred_lft = 30)
device.remove_address('2002:4BC:1::1/64')

Since fc00::/7 is the local IPv6 address range, we have also told to kernel not to accept any packets from devices that are not directly connected to us (scope = 'Link').

$ ip address show dev wlan0
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    …
    inet6 fe90::223:14ff:feb9:384/64 scope link dynamic wlan0
       valid_lft 25sec preferred_lft 25sec
    …

Querying all IP addresses

Check out the print_all example.

API documentation

class netlink.Network
device(identifier)

Obtain NetworkDevice instance for this network interface client

Parameters:identifier (int|str) – The name or index of the network device
Returns:NetworkDevice
device_index2name(index)

Obtain the name for the network device with the given interface number

Parameters:

index (int) – The interface number of the network device

Raises:

OSError – System error reported during look up

This usually means that there is no device with such number or that the interface does not have a name (since it is in another container for instance).

Returns:

str

device_name2index(name)

Obtain the index of the network device with the given interface name

Parameters:

name (str) – The name of the network interface

Raises:

OSError – System error reported during look up

This usually means that there is no device with such number or that the interface does not have a name (since it is in another container for instance).

Returns:

int

get_addresses()

Get all network addresses of all devices

Returns:collections.OrderedDict – Dictionary of device objects and addresses
Keys (NetworkDevice):
NetworkDevice objects, each representing a network interface
Values (collections.OrderedDict):
Network address to attribute mappings as described in the documentation of the netlink.NetworkDevice.get_addresses() method
get_interfaces()
get_interfaces_with_addresses()

Get all network device along with their interface attributes and their addresses

This is a convinience method that merges the results of get_addresses() and get_interfaces(). This method is a lot more efficient to use when performing look up of both network interface and network address information compared to using get_interfaces() to obtain the network device list and then calling netlink.NetworkDevice.get_addresses() on each result.

class netlink.NetworkDevice(index, name, network)
add_address(address, *args, **kwargs)

Add a new IP address to this interface

Parameters:
  • address (str | ipaddress.ip_interface()) –

    An IP address (optionally) including the network prefix

    The string must be in the form of address/prefix_len. Where address is an IP address in the form of a.b.c.d or a:b:c:d:e::f and prefix_len is the number of network address bits. If prefix_len is omitted then a prefix length of 32 bits for IPv4 and 128 bits for IPv6 will be assumed.

  • flags (collections.abc.Sequence) –

    A list of flags to enable for this address

    Currently the following flags are known:

    • 'HomeAddress': (IPv6 only)

      Designate this address the “home address” (as defined in RFC 6275#section-6.3).

    • 'ManageTempAddr': (IPv6 only)

      Make the kernel manage temporary addresses created from this one as template on behalf of Privacy Extensions (RFC 3041).

      For this to become active, the use_tempaddr sysctl setting has to be set to a value greater than zero and the given address needs to have a prefix length of exactly 64. This flag allows to use privacy extensions in a manually configured network, just like if stateless auto-configuration was active.

    • 'NoDAD': (IPv6 only)

      Do not perform Duplicate Address Detection (RFC 4862#section-5.4).

    • 'NoPrefixRoute':

      Do not automatically create a route for the network prefix of the added address, and don’t search for one to delete when removing the address.

      Modifying an address to add this flag will remove the automatically added prefix route, modifying it to remove this flag will create the prefix route automatically.

  • scope (int|str) –

    The “distance” from this host to the next host on the network represented by address

    If this is a string is must have one of the following values:

    • 'Universe': (0)

      Address points to some host far, far away (default)

    • 'Site': (200)

      Address points to a host that is located somewhere on the same network area (like a server in the next room of the same data center)

    • 'Link': (253)

      Address points to a host that is directly connected to this network host (using this network link)

    • 'Host': (254)

      Address points to this host (loopback address)

    • 'Nowhere': (255)

      Reserved for non-existing destinations

    Intermediate (numeric) values, that are not listed here, are also possible. This can be used, for instance, to declare interior routes between 'Universe' and 'Link'.

  • peer (str | ipaddress.ip_address()) –

    The address of the remote endpoint for point-to-point interfaces

  • broadcast (str | ipaddress.ip_address()) –

    The broadcast address on the interface

    The broadcast address is the address used when your host wants to comunicate with all devices on the local network.

  • anycast (str | ipaddress.ip_address()) –
  • label (str) –

    Custom label that may be used to tag individual addresses

    The label may only be up to 16 characters in length.

  • valid_lft (int) –

    The valid lifetime (in seconds) of this address

    When this value reaches 0, then this address is removed by the kernel.

    For details on lifetime handling please read RFC 4862#section-5.5.4

  • preferred_lft (int) –

    The preferred lifetime (in seconds) of this address

    When this value reaches 0, then this address won’t be used for any new outgoing connections. This value must always be smaller than valid_lft.

    For details on lifetime handling please read RFC 4862#section-5.5.4.

get_addresses()

Obtain all network addresses associated with this interface

Returns a dictionary of network addresses and a dictionary of attributes of each address.

List of known attributes:

  • 'ADDRESS': (str) – The network address itself

  • 'LOCAL': (str) – The local network address

    Unless this device is connected to a network tunnel this will always be the same as the value in 'ADDRESS'.

  • 'PREFIXLEN' (int) – The length of the common network prefix in bits

  • 'FAMILY' (int) – The address family value as integer

    Use the AF_* constants from the socket module to determine the address family type.

  • 'FLAGS' (list) – Flags set on the interface

    See the flags parameter of add_address() for a list of possible values.

  • 'INDEX' (int) – The numerical index of the network device containing this address

  • 'SCOPE' (str | int) – Network address distance

    See the scope parameter of add_address() for details.

  • 'LABEL' (str) – Custom free-text label attached to this address

    See the label parameter of add_address() for information.

  • 'CACHEINFO' (dict) – Lifetime related attributes of this address:

Example result of using get_addresses() on the loopback interface (lo):

{
    '127.0.0.1': {
        'ADDRESS':   '127.0.0.1',
        'LOCAL':     '127.0.0.1',
        'PREFIXLEN': 8,
        'FAMILY':    2,
        'FLAGS':     ['PERMANENT'],
        'INDEX':     1,
        'SCOPE':     'HOST',
        'LABEL':     'lo',
        'CACHEINFO': {'cstamp': 602, 'preferred': 4294967295, 'tstamp': 1407340, 'valid': 4294967295}
    },
    '::1': {
        'ADDRESS':   '::1',
        'PREFIXLEN': 128,
        'FAMILY':    10,
        'FLAGS':     ['PERMANENT'],
        'INDEX':     1,
        'SCOPE':     'HOST',
        'CACHEINFO': {'cstamp': 602, 'preferred': 4294967295, 'tstamp': 602, 'valid': 4294967295}
    }
}

See the print_all example for a more elaborate code sample.

Returns:dict
get_interface()
get_statistics()

Retrieve all available statistical information for the associated network interface

Returns:dict
modify_address(address, *args, create=False, **kwargs)

Modify the flags of an existing IP address

Parameters:create (bool) –

Add a new address to this interface, if no matching address exists

See add_address() for a description of other possible parameters.

remove_address(address)

Remove the given IP address from this interface

Parameters:address (str | ipaddress.ip_interface()) –

An IP address (optionally) including the network prefix

The string must be in the form of address/prefix_len. Where address is an IP address in the form of a.b.c.d or a:b:c:d:e::f and prefix_len is the number of network address bits. If prefix_len is omitted then a prefix length of 32 bits for IPv4 and 128 bits for IPv6 will be assumed.