-
Notifications
You must be signed in to change notification settings - Fork 0
/
localini.go
90 lines (82 loc) · 1.56 KB
/
localini.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"net"
"github.com/google/gopacket/pcap"
)
type localini struct {
IP net.IP
MAC net.HardwareAddr
DevName string
Name string
}
func (l *localini) set(s string) error {
ip := net.ParseIP(s)
switch ip {
case nil:
ifi, err := net.InterfaceByName(s)
if err != nil {
return nil
}
l.MAC, l.Name = ifi.HardwareAddr, ifi.Name
addrs, err := ifi.Addrs()
if err != nil {
return err
}
if addrs == nil {
return fmt.Errorf("no address found for interface: %s details: %+v", s, l)
}
for _, ipa := range addrs {
ip, _, err := net.ParseCIDR(ipa.String())
if ip.To4() == nil || err != nil {
continue
}
l.IP = ip
break
}
default:
l.IP = ip
if err := l.findMAC(); err != nil {
return err
}
}
if err := l.findDevName(); err != nil {
return err
}
return nil
}
func (l *localini) findDevName() error {
ifis, err := pcap.FindAllDevs()
if err != nil {
return err
}
for _, ifi := range ifis {
for _, a := range ifi.Addresses {
if l.IP.Equal(a.IP) {
l.DevName = ifi.Name
return nil
}
}
}
return fmt.Errorf("no interface matched input ip: %+v", l)
}
func (l *localini) findMAC() error {
ifis, err := net.Interfaces()
if err != nil {
return err
}
for _, ifi := range ifis {
addrs, err := ifi.Addrs()
if err != nil {
return err
}
for _, addr := range addrs {
ip, _, _ := net.ParseCIDR(addr.String())
if l.IP.Equal(ip) {
l.MAC, l.Name = ifi.HardwareAddr, ifi.Name
return nil
}
}
}
return fmt.Errorf("could not find local interface: %+v", err)
}