88 lines
1.5 KiB
Go
88 lines
1.5 KiB
Go
|
package slimming
|
||
|
|
||
|
import (
|
||
|
"log"
|
||
|
"time"
|
||
|
|
||
|
"github.com/songgao/packets/ethernet"
|
||
|
"github.com/songgao/water"
|
||
|
)
|
||
|
|
||
|
type NetCard struct {
|
||
|
FrameChan chan [][]byte
|
||
|
ifce *water.Interface
|
||
|
}
|
||
|
|
||
|
var netCard = func() *NetCard {
|
||
|
config := water.Config{
|
||
|
DeviceType: water.TAP,
|
||
|
}
|
||
|
config.Name = "stap"
|
||
|
|
||
|
ifce, err := water.New(config)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
nc := &NetCard{
|
||
|
FrameChan: make(chan [][]byte, 2000),
|
||
|
ifce: ifce,
|
||
|
}
|
||
|
|
||
|
go nc.RunRead()
|
||
|
go nc.RunWrite()
|
||
|
|
||
|
time.Sleep(time.Second)
|
||
|
return nc
|
||
|
}()
|
||
|
|
||
|
func GetNetCard() *NetCard {
|
||
|
return netCard
|
||
|
}
|
||
|
|
||
|
func (nc *NetCard) RunRead() {
|
||
|
|
||
|
var ifce *water.Interface = nc.ifce
|
||
|
var ticker time.Ticker = *time.NewTicker(time.Millisecond * 20)
|
||
|
for {
|
||
|
|
||
|
var framesBytes [][]byte
|
||
|
for range ticker.C {
|
||
|
var rframe ethernet.Frame
|
||
|
rframe.Resize(1500)
|
||
|
n, err := ifce.Read([]byte(rframe))
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
rframe = rframe[:n]
|
||
|
framesBytes = append(framesBytes, []byte(rframe))
|
||
|
}
|
||
|
|
||
|
if len(framesBytes) > 0 {
|
||
|
rpcServer.FrameChan <- framesBytes
|
||
|
}
|
||
|
|
||
|
// 写到grpc服务
|
||
|
|
||
|
// log.Printf("Dst: %s\n", rframe.Destination()[0:4])
|
||
|
// log.Printf("Src: %s\n", rframe.Source()[0:4])
|
||
|
// log.Printf("Ethertype: % x\n", rframe.Ethertype())
|
||
|
// log.Printf("Payload: % x\n", rframe.Payload())
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (nc *NetCard) RunWrite() {
|
||
|
var ifce *water.Interface = nc.ifce
|
||
|
|
||
|
for wframes := range nc.FrameChan {
|
||
|
for _, wframe := range wframes {
|
||
|
_, err := ifce.Write(wframe)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|