golang使用gopacket包进行数据包捕获实践(未成功)
想用go抓TCP包,参考:https://www.cnblogs.com/lanyangsh/p/9821106.html,结果运行时提示wpcap.dll有问题,从网上下载了几个都不行。后来安装了win10Pcap,似乎可以了。但又提示:Error opening adapter: �����ɹ����ɡ� (0)
改为参考:https://blog.csdn.net/warrior_0319/article/details/83150408
1、获取所有的网络设备信息,代码:
package main import ( "fmt" "log" "github.com/google/gopacket/pcap" ) func main() { // Find all devices devices, err := pcap.FindAllDevs() if err != nil { log.Fatal(err) } // Print device information fmt.Println("Devices found:") for _, device := range devices { fmt.Println("\nName: ", device.Name) fmt.Println("Description: ", device.Description) fmt.Println("Devices addresses:", device.Description) for _, address := range device.Addresses { fmt.Println("- IP address: ", address.IP) fmt.Println("- Subnet mask: ", address.Netmask) } } }
2 打开设备实时捕捉,代码:
package main import ( "fmt" "log" "time" "github.com/google/gopacket" "github.com/google/gopacket/pcap" ) var ( device string = "eth0" snapshot_len int32 = 1024 promiscuous bool = false err error timeout time.Duration = 30 * time.Second handle *pcap.Handle ) func main() { // Open device handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout) if err != nil { log.Fatal(err) } defer handle.Close() // Use the handle as a packet source to process all packets packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) for packet := range packetSource.Packets() { // Process packet here fmt.Println(packet) } }
然而,运行时再次遇到: Error opening adapter: �����ɹ����ɡ� (0),感觉还是Pcap的问题,从https://www.winpcap.org/install/default.htm官网重新下载安装,还不行。
3 抓取结果保存为pcap格式文件
package main import ( "fmt" "os" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" "github.com/google/gopacket/pcapgo" ) var ( deviceName string = "eth0" snapshotLen uint32 = 1024 promiscuous bool = false err error timeout time.Duration = -1 * time.Second handle *pcap.Handle packetCount int = 0 ) func main() { // Open output pcap file and write header f, _ := os.Create("test.pcap") w := pcapgo.NewWriter(f) w.WriteFileHeader(snapshotLen, layers.LinkTypeEthernet) defer f.Close() // Open the device for capturing handle, err = pcap.OpenLive(deviceName, int32(snapshotLen), promiscuous, timeout) if err != nil { fmt.Printf("Error opening device %s: %v", deviceName, err) os.Exit(1) } defer handle.Close() // Start processing packets packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) for packet := range packetSource.Packets() { // Process packet here fmt.Println(packet) w.WritePacket(packet.Metadata().CaptureInfo, packet.Data()) packetCount++ // Only capture 100 and then stop if packetCount > 100 { break } } }
同样是: Error opening adapter: �����ɹ����ɡ� (0)
大概需要改用wireshark了