前提:
安裝好 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.
則是因爲 ubuntu 中沒有安裝 git ,需要去安裝,命令如下:
sudo apt install git
- 如果是提示
Command 'go' not found
,則需要輸入命令:
source /etc/profile
- 如果一直下載不成功的話,則是因爲被牆了,這個解決方式因人而異,總體上就是設置代理之類的
二、進行測試
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 address
去判斷,以192開頭的一般就是,我的是 ens33
。
然後就在 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)
}
並且,需要在 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
則說明沒有訪問權限,此時,需要打開運行程序所生成的 build
文件,在終端中用root
用戶,cd
到 build
文件所在路徑,之後 通過 ./文件
運行即可!
例如:./go_build_main_go