How to create two tun for communication? What does point-to-point mean?

506 Views Asked by At

In order to implement a tcp stack in userspace, I try to set two tun device and exechange data between them for testing code.However, it seems like that all IP packet wrote to tun are dropped.

For example:

tun0,ip:172.19.16.1/20.

tun1,ip:172.19.32.1/20.

when I use ping 172.19.16.2,tun 0 can receive ICMP packet(from 172.19.16.1 to 172.19.16.2) and write data to tun0 for replying. But when I try to send a ICMP from tun0 to tun1(172.19.16.1 to 172.19.32.1 or vice versa), it failed. tun1 can't receive any data! Why? I try to send TCP packet from tun1 to tun0, it also failed.

From kernel document,I know tun is a point-to-point device and haven't mac address and arp. What does point-to-point mean? Can create two or three tun device for communicating each other?

import fcntl
import os
import if_tun
import ctypes

import struct
from scapy.all import *


from if_tun import IfReq, TUNSETIFF, IFF_TUN


def register_tun(name: str):
    fd = os.open("/dev/net/tun",os.O_RDWR)
    if fd < 0:
        return fd

    r = IfReq()

    ctypes.memset(ctypes.byref(r), 0, ctypes.sizeof(r))
    r.ifr_ifru.ifru_flags = IFF_TUN | 0x1000
    r.ifr_ifrn.ifrn_name = name.encode("utf-8")
    
    fcntl.ioctl(fd, TUNSETIFF,r)
    return fd


if __name__ == "__main__":
    fd = register_tun("tun2")
    if fd < 0:
        print("error")
    while True:
        type = input()
        a = IP(dst="172.19.16.1",src="172.19.32.1")/TCP()        
        a = IP(raw(a))
        a.show()
        print("write:")
        print(os.write(fd, raw(a)))
        buf = os.read(fd,1024)
        print("receive data")
        IP(raw(buf)).show()

1

There are 1 best solutions below

0
On

Are the 2 TUNs from the same machine? If so, you need to set the sysctl net.ipv4.conf.tun0.accept_local=1 on both TUNs. Otherwise, the kernel won't accept packets with a local source IP.

Source: https://unix.stackexchange.com/questions/597213/routing-all-packets-trough-tun-device-before-forwarding