-
Notifications
You must be signed in to change notification settings - Fork 1
/
pcap_writer.go
77 lines (64 loc) · 1.58 KB
/
pcap_writer.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
package main
import (
"fmt"
"net"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
)
type pcapWriter struct {
handle *pcap.Handle
srcMAC net.HardwareAddr
dstMAC net.HardwareAddr
}
func newPcapWriter(ifName string, dstMAC net.HardwareAddr) (*pcapWriter, error) {
iface, err := net.InterfaceByName(ifName)
if err != nil {
return nil, err
}
handle, err := pcap.OpenLive(ifName, 1024, false, pcap.BlockForever)
if err != nil {
return nil, err
}
return &pcapWriter{
handle: handle,
srcMAC: iface.HardwareAddr,
dstMAC: dstMAC,
}, nil
}
func (w *pcapWriter) close() {
w.handle.Close()
}
func (w *pcapWriter) write(srcAddr *net.UDPAddr, data []byte) error {
dstAddr := routeMapLookup(srcAddr.IP)
if dstAddr == nil {
return fmt.Errorf("No collector configured for agent %s", srcAddr.IP.String())
}
buf := gopacket.NewSerializeBuffer()
serializeOpts := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
eth := &layers.Ethernet{
SrcMAC: w.srcMAC,
DstMAC: w.dstMAC,
EthernetType: layers.EthernetTypeIPv4,
}
ip := &layers.IPv4{
SrcIP: srcAddr.IP,
DstIP: dstAddr.IP,
Protocol: layers.IPProtocolUDP,
Version: 4,
TTL: 32,
}
udp := &layers.UDP{
SrcPort: layers.UDPPort(srcAddr.Port),
DstPort: layers.UDPPort(dstAddr.Port),
}
udp.SetNetworkLayerForChecksum(ip)
payload := gopacket.Payload(data)
if err := gopacket.SerializeLayers(buf, serializeOpts, eth, ip, udp, payload); err != nil {
return err
}
return w.handle.WritePacketData(buf.Bytes())
}