yuchat-proxy/eth/eth.go
lqyan 923c68a2ea feat(vpn服务器): VPN 服务器的简单实现
WebSocket的数据写入网卡,将网卡读取的数据写入WebSocket
2024-11-15 23:03:26 +08:00

55 lines
988 B
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 eth
import (
"log"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
"github.com/gorilla/websocket"
)
const (
interfaceName = "eth0"
)
type Eth struct {
Handle *pcap.Handle
}
func Init() *Eth {
handle, err := pcap.OpenLive(interfaceName, 1600, true, pcap.BlockForever)
if err != nil {
log.Fatal("打开驱动器失败: ", err)
return nil
}
return &Eth{Handle: handle}
}
/**
* 抓取网卡的数据并写入WebSocket
*/
func (eth *Eth) EthernetPacketsToWs(wsConn *websocket.Conn) error {
packetSource := gopacket.NewPacketSource(eth.Handle, eth.Handle.LinkType())
for packet := range packetSource.Packets() {
wsConn.WriteMessage(websocket.BinaryMessage, packet.Data())
}
return nil
}
/**
* 将ws的数据写入网卡
*/
func (eth *Eth) WsToEthernet(wsConn *websocket.Conn) {
for {
_, p, err := wsConn.ReadMessage()
if err != nil {
return
}
err = eth.Handle.WritePacketData(p)
if err != nil {
log.Fatal(err)
}
}
}