<p>您可以使用tun/tap设备,只需从python中读取它,例如:</p>
<p>隧道.py</p>
<pre><code>import os
from fcntl import ioctl
from select import select
import struct
import subprocess
TUNSETIFF = 0x400454ca
TUNMODE = 0x0001
tunFile = os.open("/dev/net/tun", os.O_RDWR)
ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "tun%d", TUNMODE))
ifname = ifs[:16].strip("\x00")
print "Allocated interface %s. Configure it and use it" % ifname
subprocess.call("ifconfig %s 192.168.13.1" % ifname,shell=True)
# Reading
def read():
r = select([tunFile], [], [])[0][0]
if r == tunFile:
return os.read(tunFile, 1600)
return None
# Writing
def write(buf):
os.write(tunFile, buf)
</code></pre>
<p>完整的示例可以找到<a href="http://www.secdev.org/projects/tuntap_udp/" rel="nofollow">here</a></p>
<p>并将数据包路由到接口“tun0”或打印的inetrface名称。</p>
<p>linux发行版不需要安装任何东西,但如果您在windows上,请使用<a href="http://www.varsanofiev.com/inside/using_tuntap_under_windows.htm" rel="nofollow">this</a>,对于mac os,请使用<a href="http://tuntaposx.sourceforge.net/" rel="nofollow">this</a></p>
<p>编辑1
来自<a href="http://backreference.org/2010/03/26/tuntap-interface-tutorial/" rel="nofollow">here</a>的注释:</p>
<blockquote>
<p>The difference between a tap interface and a tun interface is that a tap interface outputs (and must be given) full ethernet frames, while a tun interface outputs (and must be given) raw IP packets (and no ethernet headers are added by the kernel). Whether an interface functions like a tun interface or like a tap interface is specified with a flag when the interface is created.</p>
</blockquote>
<p>要查找数据包头信息(如src、dst等),可以使用<a href="http://code.google.com/p/dpkt/" rel="nofollow">dpkt</a></p>
<pre><code>from dpkt import ip
from tunnel import read,write # tunnel.py
while 1:
data = read()
if data:
ipObj = ip.IP(data[4:])
print ipObj.src, ipObj.dst
</code></pre>