-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathsocket_linux.go
More file actions
79 lines (71 loc) · 1.63 KB
/
Copy pathsocket_linux.go
File metadata and controls
79 lines (71 loc) · 1.63 KB
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
//go:build linux
package sonic
import (
"net"
"syscall"
"unsafe"
)
// BindToDevice binds the socket to the device with the given name. The device
// must be a network interface (`ip link` to see all interfaces).
//
// This makes it such that only packets from the given device will be processed
// by the socket.
func (s *Socket) BindToDevice(name string) (*net.Interface, error) {
iff, err := net.InterfaceByName(name)
if err != nil {
return nil, err
}
if err := syscall.SetsockoptString(
s.fd,
syscall.SOL_SOCKET,
syscall.SO_BINDTODEVICE,
iff.Name,
); err != nil {
return nil, err
} else {
s.boundInterface = iff
return iff, nil
}
}
// UnbindFromDevice is not working, and honestly I have no clue why.
func (s *Socket) UnbindFromDevice() error {
if s.boundInterface == nil {
return nil
}
/* #nosec G103 -- the use of unsafe has been audited */
_, _, errno := syscall.Syscall6(
uintptr(syscall.SYS_SETSOCKOPT),
uintptr(s.fd),
uintptr(syscall.SOL_SOCKET),
uintptr(syscall.SO_BINDTODEVICE),
uintptr(unsafe.Pointer(&[]byte("_")[0])),
0, 0,
)
if errno != 0 {
err := errno
return err
} else {
s.boundInterface = nil
return nil
}
}
func GetBoundDevice(fd int) (string, error) {
into := make([]byte, syscall.IFNAMSIZ)
n := 0
/* #nosec G103 -- the use of unsafe has been audited */
_, _, errno := syscall.Syscall6(
uintptr(syscall.SYS_GETSOCKOPT),
uintptr(fd),
uintptr(syscall.SOL_SOCKET),
uintptr(syscall.SO_BINDTODEVICE),
uintptr(unsafe.Pointer(&(into[0]))),
uintptr(unsafe.Pointer(&n)),
0,
)
if errno != 0 {
err := errno
return "", err
} else {
return string(into[:n]), nil
}
}