tun/tap 是操作系统内核中的虚拟网络设备。tap 等同于一个以太网设备,它操作第二层数据包如以太网数据帧。tun 模拟了网络层设备,操作第三层数据包比如IP数据封包。
tun 设备
- linux 下创建命令:
# add tun
sudo ip tuntap add tun0 mode tun
# del tun
sudo ip tuntap del tun0 mode tun
- golang 创建
import (
"fmt"
"github.com/songgao/packets/ethernet"
"github.com/songgao/water"
"time"
)
func main() {
tapconfig := water.Config{
DeviceType: water.TAP,
PlatformSpecificParams: water.PlatformSpecificParams{
Name: "tun0",
},
}
ifce, err := water.New(tapconfig)
if err != nil {
fmt.Printf("创建失败:%v \n", err)
return
}
var buf ethernet.Frame
for {
_, err := ifce.Read(buf)
if err != nil {
fmt.Printf("读取数据:%v \n", err)
return
}
time.Sleep(time.Second)
}
}
tap 设备
- linux 下创建命令:
# add tap
sudo ip tuntap add tap0 mode tap
# del tap
sudo ip tuntap del tap0 mode tap
- golang 创建
import (
"fmt"
"github.com/songgao/packets/ethernet"
"github.com/songgao/water"
"time"
)
func main() {
tapconfig := water.Config{
DeviceType: water.TAP,
PlatformSpecificParams: water.PlatformSpecificParams{
Name: "tap0",
Persist: true,
},
}
ifce, err := water.New(tapconfig)
if err != nil {
fmt.Printf("创建失败:%v \n", err)
return
}
var buf ethernet.Frame
for {
_, err := ifce.Read(buf)
if err != nil {
fmt.Printf("读取数据:%v \n", err)
return
}
time.Sleep(time.Second)
}
}