dae/pkg/ebpf_internal/rawsock.go

32 lines
788 B
Go
Raw Normal View History

2023-01-30 22:21:00 +07:00
// Copied from https://github.com/cilium/ebpf/blob/v0.10.0/example_sock_elf_test.go
package internal
import (
2023-02-25 01:38:21 +07:00
"encoding/binary"
2023-01-30 22:21:00 +07:00
"syscall"
2023-02-25 01:38:21 +07:00
"unsafe"
2023-01-30 22:21:00 +07:00
)
2023-02-25 01:38:21 +07:00
// Htons converts the unsigned short integer hostshort from host byte order to network byte order.
func Htons(i uint16) uint16 {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, i)
return *(*uint16)(unsafe.Pointer(&b[0]))
}
2023-01-30 22:21:00 +07:00
func OpenRawSock(index int) (int, error) {
2023-02-25 01:38:21 +07:00
sock, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, int(Htons(syscall.ETH_P_ALL)))
2023-01-30 22:21:00 +07:00
if err != nil {
return 0, err
}
sll := syscall.SockaddrLinklayer{
Ifindex: index,
2023-02-25 01:38:21 +07:00
Protocol: Htons(syscall.ETH_P_ALL),
2023-01-30 22:21:00 +07:00
}
if err := syscall.Bind(sock, &sll); err != nil {
return 0, err
}
return sock, nil
}