Skip to content
Peter V. Saveliev edited this page May 17, 2016 · 4 revisions

IPRoute batch mode

… as a netlink packet compiler:

$ python3
Python 3.4.3 (default, Mar 31 2016, 20:42:37) 
[GCC 5.3.1 20151207 (Red Hat 5.3.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyroute2 import IPBatch
>>> from pyroute2.common import hexdump
>>> ip = IPBatch()
>>> ip.link("add", index=550, ifname="test", kind="dummy")
>>> ip.link("set", index=550, state="up")
>>> ip.addr("add", index=550, address="10.0.0.2", mask=24)
>>> print(hexdump(ip.batch))
3c:00:00:00:10:00:05:06:00:00:00:00:3a:17:00:00:00:00:00:00:26:02:00:00:00:00:00:
00:00:00:00:00:09:00:03:00:74:65:73:74:00:00:00:00:10:00:12:00:0a:00:01:00:64:75:
6d:6d:79:00:00:00:20:00:00:00:13:00:05:06:00:00:00:00:3a:17:00:00:00:00:00:00:26:
02:00:00:01:00:00:00:01:00:00:00:28:00:00:00:14:00:05:06:00:00:00:00:3a:17:00:00:
02:18:00:00:26:02:00:00:08:00:01:00:0a:00:00:02:08:00:02:00:0a:00:00:02
>>> 

… to speed up netlink request:

##
# experimental code
#
# the «parser2» branch
from pyroute2.iproute import IPBatch
from pyroute2.iproute import IPRoute

ipr = IPRoute()  # an ordinary IPRoute object
b = IPBatch()    # a batch object with the same API as IPRoute

# create a dummy interface «test»
ipr.link("add", ifname="test", kind="dummy")
idx = ipr.link_lookup(ifname="test")[0]

for i in range(2, 255):
    # add an IPv4 address to the batch request
    b.addr("add", index=idx, address="10.0.0.%i" % i, mask=24)
    # the difference:
    # IPRoute.addr("add", …) would send the request immediately
    # IPBatch.addr("add", …) only compiles the buffer
    # one can send it later via IPRoute.sendto(…)

# send all the compiled packets at once as one data chunk
ipr.sendto(b.batch, (0, 0))
b.reset()  # reset the batch buffer
ipr.close()
Clone this wiki locally