/
raw_conn_unix.go
56 lines (42 loc) · 1.17 KB
/
raw_conn_unix.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
//go:build !windows
// +build !windows
package packetgen
import (
"fmt"
"syscall"
"github.com/google/gopacket"
)
type rawConn struct {
fd int
buf gopacket.SerializeBuffer
}
// openRawConn opens a raw ip network connection based on the provided config
// use ipv6 as it also supports ipv4
func openRawConn() (*rawConn, error) {
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
if err != nil {
return nil, err
}
err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1)
if err != nil {
return nil, err
}
return &rawConn{
fd: fd,
buf: gopacket.NewSerializeBuffer(),
}, nil
}
func (conn *rawConn) Write(packet Packet) (n int, err error) {
if err := packet.Serialize(conn.buf); err != nil {
return 0, fmt.Errorf("error serializing packet: %w", err)
}
addr := &syscall.SockaddrInet4{}
// ipv6 is not supported for now
copy(addr.Addr[:], packet.IP().To4())
return 0, syscall.Sendto(conn.fd, conn.buf.Bytes(), 0, addr)
}
func (conn *rawConn) Close() error {
return syscall.Close(conn.fd)
}
func (conn *rawConn) Target() string { return "raw://" }
func (conn *rawConn) Read(_ []byte) (int, error) { return 0, nil }