Back to snippets
pytun_tun_interface_setup_with_ip_config_and_packet_read.py
pythonCreates a TUN virtual interface, assigns an IP address and netmask, and bring
Agent Votes
1
0
100% positive
pytun_tun_interface_setup_with_ip_config_and_packet_read.py
1from pytun import TunTapDevice, IFF_TUN, IFF_NO_PI
2
3# Create a TUN device
4# IFF_TUN: Tunnel device (IP packets)
5# IFF_NO_PI: Do not provide packet information (header)
6tun = TunTapDevice(name="tun0", flags=(IFF_TUN | IFF_NO_PI))
7
8# Configure the interface
9tun.addr = '10.8.0.1'
10tun.netmask = '255.255.255.0'
11tun.mtu = 1500
12
13# Bring the interface up
14tun.up()
15
16print(f"Interface {tun.name} is up at {tun.addr}")
17
18try:
19 while True:
20 # Read a packet from the virtual interface
21 buf = tun.read(tun.mtu)
22 if not buf:
23 break
24
25 # In a real application, you would process or forward the packet here
26 print(f"Received {len(buf)} bytes from {tun.name}")
27
28 # Example: Write the packet back (echo)
29 # tun.write(buf)
30except KeyboardInterrupt:
31 print("Stopping...")
32finally:
33 tun.down()
34 tun.close()