vnic/examples/basic/main.go

92 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"git.kingecg.top/kingecg/vnic"
)
func main() {
// 创建虚拟网卡配置
config := vnic.Config{
IP: "192.168.100.1/24", // 设置虚拟网卡的IP地址和子网掩码
}
// 创建虚拟网卡
log.Println("正在创建虚拟网卡...")
nic, err := vnic.New(config)
if err != nil {
log.Fatalf("创建虚拟网卡失败: %v", err)
}
// 确保程序退出时关闭虚拟网卡
defer func() {
log.Println("正在关闭虚拟网卡...")
if err := nic.Close(); err != nil {
log.Printf("关闭虚拟网卡时出错: %v", err)
}
}()
log.Printf("虚拟网卡创建成功,接口名称: %s", nic.Name())
// 创建一个通道来监听系统信号
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
// 启动一个goroutine来读取数据包
go func() {
buffer := make([]byte, 2000)
for {
n, err := nic.Read(buffer)
if err != nil {
log.Printf("读取数据包时出错: %v", err)
return
}
log.Printf("收到数据包: %d 字节", n)
// 在实际应用中这里可以解析和处理IP数据包
// 例如解析IP头部、提取源/目标地址等
}
}()
// 每隔5秒发送一个测试数据包
go func() {
// 创建一个简单的ICMP Echo请求数据包ping
// 注意:这只是一个示例,实际上这个数据包格式不完整
icmpPacket := []byte{
0x45, 0x00, 0x00, 0x1c, // IP头: 版本、服务类型、总长度
0x12, 0x34, 0x00, 0x00, // IP头: 标识、标志、片偏移
0x40, 0x01, 0x00, 0x00, // IP头: TTL、协议(ICMP=1)、校验和
0xc0, 0xa8, 0x64, 0x01, // IP头: 源IP (192.168.100.1)
0xc0, 0xa8, 0x64, 0x02, // IP头: 目标IP (192.168.100.2)
0x08, 0x00, 0x00, 0x00, // ICMP: 类型(Echo请求)、代码、校验和
0x00, 0x01, 0x00, 0x01, // ICMP: 标识符、序列号
}
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
_, err := nic.Write(icmpPacket)
if err != nil {
log.Printf("发送数据包时出错: %v", err)
} else {
log.Println("已发送测试数据包")
}
}
}
}()
// 等待中断信号
<-sigCh
fmt.Println("\n收到中断信号程序退出")
}