Python implements TUN/TAP virtual devices __python

Source: Internet
Author: User

working with the use of Tap/tun devices to achieve virtual networks, see the online examples are implemented in C. The main thing to try to do with Python is to reuse the ctypes definition of the relevant structure.

code GitHub Address:

Https://github.com/happyAnger6/network_programming


This git library will continue to use Python to implement network-related programming.


if_tun.py: Is mainly related to the definition of structural body.

Import ctypes Import Ioctl_def Tunsetiff=ioctl_def._iow (ord (' T '),, Ctypes.c_int) iff_tun=1 iff_tap=2 ifnamsiz=16 cl Ass sockaddr (ctypes. Structure): _fields_=[("sa_family", Ctypes.c_ushort), ("Sa_data", ctypes.c_char*14)] class Ifmap (ctypes. Structure): _fields_=[("Mem_start", Ctypes.c_ulong), ("Mem_end", Ctypes.c_ulong), ("Base_addr", Ctypes.c_ushort ("IRQ", Ctypes.c_char), ("DMA", Ctypes.c_char), ("Port", Ctypes.c_char)] class IFS_IFSU (ctypes. Union): _fields_=[("RAW_HDLC", ctypes.c_void_p), ("Cisco", Ctypes.c_void_p), ("fr", ctypes.c_void_p), ("fr _PVC ", ctypes.c_void_p), (" Fr_pvc_info ", ctypes.c_void_p), (" Sync ", ctypes.c_void_p), (" Te1 ", ctypes.c_void _p)] class ifsettings (ctypes. Structure): _fields_=[("type", Ctypes.c_uint), ("Size", Ctypes.c_uint), ("IFS_IFSU", IFS_IFSU)] class Ifr_ifru (cTYPES.
Union): _fields_=[("Ifru_addr", sockaddr), ("Ifru_dstaddr", sockaddr), ("Ifru_broadaddr", sockaddr),			  ("Ifru_netmask", sockaddr), ("Ifru_hwaddr", sockaddr), ("Ifru_flags", Ctypes.c_ushort), ("Ifru_ivalue" 
			  , Ctypes.c_int), ("Ifru_mtu", Ctypes.c_int), ("Ifru_map", Ifmap), ("Ifru_slave", Ctypes.c_char * ifnamsiz), 

("Ifru_newname", Ctypes.c_char * ifnamsiz), ("Ifru_data", ctypes.c_void_p), ("Ifru_settings", Ifsettings)] Class IFR_IFRN (cTYPES. Union): _fields_=[("Ifrn_name", Ctypes.c_char * ifnamsiz)] class Ifreq (ctypes. Structure): _fields_=[("IFR_IFRN", IFR_IFRN), ("Ifr_ifru", Ifr_ifru)] If __name__ = "__main__": Ifreq = Ifreq () pr Int (ctypes.sizeof (IFREQ.IFR_IFRN)) print (ctypes.sizeof (IFREQ.IFR_IFRU))

ioctl_def.py: Mainly the IOCTL command word related definition:

_ioc_nrbits=8 _ioc_typebits=8 _ioc_sizebits=14 _ioc_dirbits=2 _ioc_nrmask= ((1 << _ioc_nrbits)-1) _IOC_TYPEMASK= ((1 << _ioc_typebits)-1) _ioc_sizemask= ((1 << _ioc_sizebits)-1) _ioc_dirmask= ((1 << _ioc_dirbits)- 1) _ioc_nrshift=0 _ioc_typeshift= (_ioc_nrshift + _ioc_nrbits) _ioc_sizeshift= (_ioc_typeshift + _IOC_TYPEBITS) _IOC_ dirshift= (_ioc_sizeshift + _ioc_sizebits) _ioc_none=0 _ioc_write=1 _ioc_read=2 def _ioc (dir, type, nr, size): Return ( (dir) << _ioc_dirshift | \ (type) << _ioc_typeshift | ((NR) << _ioc_nrshift |
	\ (size) << _ioc_sizeshift) import ctypes def _ioc_typecheck (t): return ctypes.sizeof (t) def _io (Type, NR): Return _ioc (_ioc_none, type, nr, 0) def _ior (type, nr, size): Return _ioc (_ioc_read, type, nr, _ioc_typecheck (size)) d EF _iow (Type, nr, size): Return _ioc (_ioc_write, type, nr, _ioc_typecheck (size)) If __name__ = "__main__": Print (_IOC_ Typeshift,_ioc_sizeshift,_ioc_dirshift) Print (_IOC ()) 

tun_oper.py: Create a Tun device and listen for data sending requests.

Import fcntl Import
os

import ctypes
import struct from

If_tun import ifreq, Tunsetiff, Iff_tun

def Tun_create (Devname, flags):
	FD =-1
	if not devname:
		return-1
	fd = Os.open ("/dev/net/tun", OS. O_RDWR)
	If fd < 0:
		print ("Open/dev/net/tun err!")
		return FD
	r=ifreq ()
	Ctypes.memset (Ctypes.byref (R), 0, ctypes.sizeof (r))
	R.ifr_ifru.ifru_flags |= Flags
	r.ifr_ifrn.ifrn_name = Devname.encode (' utf-8 ')
	try:
		err = Fcntl.ioctl (FD, Tunsetiff, R)
	Except Exception as E:
		print ("ERR:", e)
		os.close (FD)
		return-1 return
	fd

if __name__ = = "__ main__ ":
	fd = tun_create (" Tun3 ", Iff_tun)
	if FD < 0: Raise OSError maxsize=4096 while
	( True):
		buf = Os.read (fd,maxsize)
		if not buf:
			break
print ("read size:%d"% len (BUF))

Test:

to set IP for a tun3 device:

#ifconfig Tun3 10.0.0.1 up

to add a static route, forward via TUN3:

#route add-net 10.0.0.2 netmask 255.255.255.255 Dev tun3

Ping An address to send data to TUN3:

#ping 10.0.0.2

Tun3 received the data:

Read size:88
Read size:88
Read size:88
Read size:88
Read size:88
Read size:88
Read size:88
Read size:88


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.