-
Notifications
You must be signed in to change notification settings - Fork 25
/
rawsocket.go
47 lines (38 loc) · 838 Bytes
/
rawsocket.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
package main
import (
"net"
"syscall"
"github.com/google/gopacket/pcapgo"
)
type rawSocket struct {
reader *pcapgo.EthernetHandle
writer int
}
func newRawSocket(intf *net.Interface) (*rawSocket, error) {
reader, err := pcapgo.NewEthernetHandle(intf.Name)
if err != nil {
return nil, err
}
writer, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, syscall.ETH_P_ALL)
if err != nil {
return nil, err
}
err = syscall.Bind(writer, &syscall.SockaddrLinklayer{
Ifindex: intf.Index,
})
if err != nil {
return nil, err
}
return &rawSocket{
reader: reader,
writer: writer,
}, nil
}
func (s *rawSocket) Read() ([]byte, error) {
byts, _, err := s.reader.ZeroCopyReadPacketData()
return byts, err
}
func (s *rawSocket) Write(byts []byte) error {
_, err := syscall.Write(s.writer, byts)
return err
}