| Version 8 (modified by thomas, 3 years ago) (diff) |
|---|
Table of Contents
Virtual Interface
Goal
Creating Virtual Network Interfaces in Linux (TUN)
For a WSN to communicate with the outside world, we typically have a border router (a Linux machine, for example) with a mote on one side and a physical network interface on the other side connected to the Internet. The picture could look like this:
We have a physical network interface connected to the Internet. We would like to have also a network interface for the WSN side. Provided the WSN runs Berkeley OpenWSN or other 6LowPAN protocol stack, direct communication to and from the Internet from motes in the WSN would be possible. If the mote presents itself to the Linux machine as a network interface, the 6LowPAN header compression can be performed at the gateway mote. If the mote does not present itself to the Linux machine as a network interface, creating a virtual network interface will be very useful as we shall see here.
What is a TUN interface/virtual network interface
A virtual network interface is a software network interface provided by the operating system to user space programs. Instead of having the packets sent across a physical network, they are captured by the user space program. The user space program may do various tasks with the captured packets, the most common being virtual private networking (VPN), but others are possible. In our case, we could have the user space program do the 6LowPAN header compression/decompression and forwarding of packets to/from the serial port to which the mote is attached. This would convert our mote into a network interface at the Linux router, enabling communication between the WSN and the Internet by just editing the kernel routing tables.
Creating and configuring a TUN interface
Here we will show how to create and configure a TUN interface in Linux. First, the tun kernel module has to be loaded, and make sure that it will load automatically at boot
# echo tun >> /etc/modules # modprobe tun
Now we create Python functions to create and configure the TUN interface:
import os
import struct
from fcntl import ioctl
IPV6PREFIX = '2001:470:1f05:98e'
IFF_TUN = 0x0001
TUNSETIFF = 0x400454ca
def tun_create():
# create interface
f = os.open("/dev/net/tun", os.O_RDWR)
ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "tun%d", IFF_TUN))
ifname = ifs[:16].strip("\x00")
# configure interface
v = os.system('ifconfig ' + ifname + ' inet6 add ' + IPV6PREFIX + '::1/64')
v = os.system('ifconfig ' + ifname + ' up')
# set route
os.system('route -A inet6 add ' + IPV6PREFIX + '::/64 dev ' + ifname)
# enable IPv6 forwarding
os.system('echo 1 > /proc/sys/net/ipv6/conf/all/forwarding')
return ifname
where we assume that the WSN has 2001:470:1f05:98e as its IPv6 prefix. We can use this code in the main program that will process our packets. The interface will dissapear once the Python program ends.


