-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (96 loc) · 2.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Package main is the example of *layers.ARP
package main
import (
"fmt"
"log"
"os"
"os/signal"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
)
var (
appLog = log.New(os.Stderr, "", 0)
)
func main() {
if err := run(); err != nil {
appLog.Panic(err)
}
}
func run() error {
const (
device = "eth0"
filter = ""
snapshotLen = int32(1600)
promiscuous = false
timeout = pcap.BlockForever
)
defer func() { appLog.Println("DONE") }()
// --------------------------------------
// Open capture handle
// --------------------------------------
var (
handle *pcap.Handle
err error
)
handle, err = pcap.OpenLive(device, snapshotLen, promiscuous, timeout)
if err != nil {
return fmt.Errorf("error open handle: %w", err)
}
defer handle.Close()
// --------------------------------------
// Apply capture filter (optional)
// --------------------------------------
if filter != "" {
err = handle.SetBPFFilter(filter)
if err != nil {
return fmt.Errorf("error apply filter: %w", err)
}
}
// --------------------------------------
// Set signal handler
// --------------------------------------
var (
sigCh = make(chan os.Signal, 1)
)
signal.Notify(sigCh, os.Interrupt)
// --------------------------------------
// Make packet source and display.
// --------------------------------------
var (
dataSource gopacket.PacketDataSource = handle
decoder gopacket.Decoder = handle.LinkType()
packetSource *gopacket.PacketSource = gopacket.NewPacketSource(dataSource, decoder)
packetCh <-chan gopacket.Packet = packetSource.Packets()
)
appLog.Println("START")
LOOP:
for {
select {
case <-sigCh:
break LOOP
case p, ok := <-packetCh:
if !ok {
break LOOP
}
// Display only the first items
if see(p) {
break LOOP
}
}
}
return nil
}
func see(p gopacket.Packet) bool {
arpLayer := p.Layer(layers.LayerTypeARP)
if arpLayer == nil {
return false
}
arp := arpLayer.(*layers.ARP)
appLog.Printf("[Operation ] %v", arp.Operation)
appLog.Printf("[Src Hw Addr ] %v", arp.SourceHwAddress)
appLog.Printf("[Src Prot Addr] %v", arp.SourceProtAddress)
appLog.Printf("[Dst Hw Addr ] %v", arp.DstHwAddress)
appLog.Printf("[Dst Prot Addr] %v", arp.DstProtAddress)
return true
}