Retry creating tun device until we find an unused name
@@ -47,11 +47,29 @@ def create_tun(name="tun0", ip="192.168.255.1"):
IFF_TUN = 0x0001
IFF_NO_PI = 0x1000
tun = open('/dev/net/tun', 'r+b')
+ tun_num = int(name.split('tun')[-1])
+
+ # Try and create tun device until we find a name not in use
+ # eg. tun0, tun1, tun2...
+ while True:
+ try:
+ name = 'tun{}'.format(tun_num)
ifr = struct.pack('16sH', name, IFF_TUN | IFF_NO_PI)
+ cocotb.log.info(name)
fcntl.ioctl(tun, TUNSETIFF, ifr)
+ break
+ except IOError as e:
+ # Errno 16 if tun device already exists, otherwise this
+ # failed for different reason.
+ if e.errno != 16:
+ raise e
+
+ tun_num += 1
+
fcntl.ioctl(tun, TUNSETOWNER, 1000)
- subprocess.check_call('ifconfig tun0 %s up pointopoint 192.168.255.2 up' %
- ip, shell=True)
+ subprocess.check_call('ifconfig %s %s up pointopoint 192.168.255.2 up' %
+ (name, ip), shell=True)
+ cocotb.log.info("Created interface %s (%s)" % (name, ip))
return tun
