golang

mac m1笔记本上使用gopacket实现抓包

1.安装libpcap

brew install libpcap

由于我之前安装了,所以这里执行了reinstall重新安装了一次

2.设置环境变量

追加如下内容到~/.zprofile中

export PATH="/opt/homebrew/opt/libpcap/bin:$PATH"
export LDFLAGS="-L/opt/homebrew/opt/libpcap/lib"
export CPPFLAGS="-I/opt/homebrew/opt/libpcap/include"

追加好之后,执行如下命令使之生效

source ~/.zprofile

3.设置go env

go env -w CGO_ENABLED=’1′

不设置会报错

报错信息如下

4.准备go项目

mkdir goPacketTest

cd goPacketTest

go mod init goPacketTest

go get github.com/google/gopacket

准备如下代码

package main

import (
	"fmt"
	"github.com/google/gopacket/pcap"
	"log"
)

var (
	pcapFile  = "vxmAndVcuSomeip.log"
	pcanFile2 = "20231213someipscripts.cap"
	handle    *pcap.Handle
	err       error
)

func main() {

	PrintAllDevice()
}

func PrintAllDevice() {
	// 得到所有的(网络)设备
	devices, err := pcap.FindAllDevs()
	if err != nil {
		log.Fatal(err)
	}
	// 打印设备信息
	fmt.Println("Devices found:")
	for _, device := range devices {
		fmt.Println("Name: ", device.Name)
		fmt.Println("Description: ", device.Description)
		for _, address := range device.Addresses {
			fmt.Println("- IP地址: ", address.IP)
			fmt.Println("- 子网掩码: ", address.Netmask)
		}
		fmt.Println("")
	}
}

测试

留言

您的邮箱地址不会被公开。 必填项已用 * 标注

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。