就我個人而言,我使用gopacket來捕獲多個網絡層,這個庫非常令人印象深刻。
當你使用gopacket,您可以通過指定他們捕捉到多個網絡層,例如Ipv4
,TCP
,Ethernet
... 欲瞭解更多信息,請參閱layers packet。
然後,您將能夠使用packet.Data()
(這是一組構成此整個數據包的字節)分析您的圖層,然後切換數據包類型以執行某些操作。
例如,捕捉多個網絡層上eth0
:
package main
import (
"fmt"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"time"
)
//Layers we want to decode
var (
ip4 layers.IPv4
eth layers.Ethernet
tcp layers.TCP
)
func main() {
//Array to store decoded layers
decodedLayers := []gopacket.LayerType{}
//Create parser
parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &tcp)
//Here we use pcap to capture packet on eth0 interface, we can also use afpacket for example, which is more efficient
handle, err := pcap.OpenLive("eth0", 65536, true, pcap.BlockForever)
if err != nil {
panic("Error opening pcap: " + err.Error())
}
datasource := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
//packets will be a channel of packets
packets := datasource.Packets()
for {
select {
case packet := <-packets:
//We are decoding layers, and switching on the layer type
err := parser.DecodeLayers(packet.Data(), &decodedLayers)
for _, typ := range decodedLayers {
switch typ {
case layers.LayerTypeIPv4:
fmt.Printf("Source ip = %s - Destination ip = %s \n", ip4.SrcIP.String(), ip4.DstIP.String())
case layers.LayerTypeTCP:
//Here, we can access tcp packet properties
fmt.Println("Capture tcp traffic")
}
//etc ....
}
if len(decodedLayers) == 0 {
fmt.Println("Packet truncated")
}
//If the DecodeLayers is unable to decode the next layer type
if err != nil {
//fmt.Printf("Layer not found : %s", err)
}
}
}
}
我看了你的筆記,但你的回答一定是最好的,因爲我想實現負載均衡我自己 –
,所以我看到和聽到了很多的數據包來了,我將它們轉發到我的服務器來處理它們並打開tcp的權利?平衡器是一個橋樑嗎? –