-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip_socket.go
76 lines (67 loc) · 1.37 KB
/
ip_socket.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
package ftcp
import (
"io"
"net"
"os"
"golang.org/x/sys/unix"
)
func OpenIPSocket(addr net.IP) (*net.IPConn, error) {
ipAddr := &net.IPAddr{
IP: addr,
Zone: "",
}
conn, err := net.ListenIP("ip4:tcp", ipAddr)
if err != nil {
return nil, err
}
rc, err := conn.SyscallConn()
if err != nil {
conn.Close()
return nil, err
}
var sockOptErr error
err = rc.Control(func(fd uintptr) {
sockOptErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_HDRINCL, 1)
})
if err != nil {
conn.Close()
return nil, err
} else if sockOptErr != nil {
conn.Close()
return nil, sockOptErr
}
return conn, nil
}
func htons(v uint16) uint16 {
return ((v & 0xFF) << 8) | ((v & 0xFF00) >> 8)
}
func OpenRawSocket() (io.ReadWriteCloser, error) {
fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_DGRAM, int(htons(unix.ETH_P_IP)))
if err != nil {
return nil, err
}
/*
ifs, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, ifi := range ifs {
log.Printf("Interface: %v", ifi)
}
*/
ifc, err := net.InterfaceByName("eno1")
if err != nil {
LogError("Interface error: %v", err)
return nil, err
}
sa := &unix.SockaddrLinklayer{
Protocol: htons(unix.ETH_P_IP),
Ifindex: ifc.Index,
}
err = unix.Bind(fd, sa)
if err != nil {
LogError("Bind error: %v", err)
return nil, err
}
return os.NewFile(uintptr(fd), "<raw socket>"), nil
}