前提:
安装好 go 环境,下载地址如下:
https://golang.google.cn/dl/
tar -zxvf
之后建立一个文件夹(我建的是 goprojects),用来存放之后的go项目
在终端里输入一下命令:
1、编辑环境变量(没有安装vim的,可以根据提示命令进行安装):
vim /etc/profile
2、设置 GOROOT以及GOPATH:
export GOPATH=/home/wyj/mine/software/goprojects
export GOROOT=/home/wyj/mine/software/go
export PATH=$PATH:/home/wyj/mine/software/go/bin
export PATH=$PATH:$GOPATH:$GOROOT:/bin
3、输入以下命令更改后的境变量生效:
source /etc/profile
测试是否安装 go 成功:
go version
之后,每次新打开一个终端,运行go命令,都需要先输入以下命令:
source /etc/profile
一、首先,下载gopacket包,libpcap库,配置下条件
在终端中输入以下命令:
# Get the gopacket package from GitHub
go get github.com/google/gopacket
# Pcap dev headers might be necessary
sudo apt-get install libpcap-dev
go: missing Git command.
sudo apt install git
Command 'go' not found
source /etc/profile
-
如果一直下载不成功的话,则是因为被墙了,这个解决方式因人而异,总体上就是设置代理之类的
-
注意: 下载的 gopacket 要存放在 GOPATH 中,如果不在,自己去移过去,不然程序无法成功导入 gopacket 相关包
二、进行测试
1、获取本机所有的网络设备信息
package main
import (
"fmt"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
"log"
"time"
)
func main() {
// Find all devices
devices, err := pcap.FindAllDevs()
if err != nil {
log.Fatal(err)
}
// Print device information
fmt.Println("Devices found:")
index:=1
for _, d := range devices {
fmt.Printf("\n%d———— Name:%s\n", index, d.Name)
fmt.Println("Description: ", d.Description)
fmt.Println("Devices addresses: ", d.Addresses)
index++
for _, address := range d.Addresses {
fmt.Println("- IP address: ", address.IP)
fmt.Println("- Subnet mask: ", address.Netmask)
}
}
}
输出如下:
2、打开设备实时捕捉数据信息
IP addressens33main
//抓包
// 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)
}
main
var (
device string = "ens33"//根据个人情况而定
snapshot_len int32 = 1024
promiscuous bool = false
err error
timeout time.Duration = 30 * time.Second
handle *pcap.Handle
)
输出获取的数据结果如下:
*****如果报以下错误 :
you don’t have permission to capture on that device
buildrootcdbuild./文件./go_build_main_go
vim /etc/sudoersroot ALL=(ALL:ALL) ALL
用户名 ALL=(ALL:ALL) ALL
再去执行 exe 文件即可!