-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconn_util.go
48 lines (43 loc) · 868 Bytes
/
conn_util.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
package main
import (
"net"
"strings"
)
// Get the bytes of an IP address from a net.Conn
func GetIP(addr net.Addr) net.IP {
straddr := addr.String()
host, _, _ := net.SplitHostPort(straddr)
idx := strings.Index(host, "%")
if idx >= 0 {
host = host[:idx]
}
ipaddr := net.ParseIP(host)
ip := ipaddr.To4()
if ip == nil {
ip = ipaddr.To16()
}
if ip == nil {
panic("Could not convert IP")
}
return ip
}
// Get the bytes of a MAC address from a net.Conn
func GetMAC(addr net.Addr) net.HardwareAddr {
ifaces, err := net.Interfaces()
ip := GetIP(addr)
if err != nil {
panic("Cannot access interfaces")
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
if strings.Index(addr.String(), ip.String()) >= 0 {
return iface.HardwareAddr
}
}
}
return nil
}