feat(vpn服务器): VPN 服务器的简单实现
WebSocket的数据写入网卡,将网卡读取的数据写入WebSocket
This commit is contained in:
54
eth/eth.go
Normal file
54
eth/eth.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user