-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInterface.go
55 lines (50 loc) · 1.16 KB
/
Interface.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
package UPnP
import (
"errors"
"net"
"strings"
)
// GetInterfaceByName get interface by name
func GetInterfaceByName(name string) (*net.Interface, error) {
Interfaces, _ := net.Interfaces()
for _, Interface := range Interfaces {
if Interface.Name == name {
return &Interface, nil
}
}
return nil, errors.New("Not found interface : " + name)
}
// GetInterfaceByIP get interface by ip 192.168.1.1 (search by contain not exactly)
func GetInterfaceByIP(ip string) (*net.Interface, error) {
Interfaces, _ := net.Interfaces()
for _, Interface := range Interfaces {
addrs, err := Interface.Addrs()
if err != nil {
continue
}
for _, add := range addrs {
if strings.Contains(add.String(), ip) {
return &Interface, nil
}
}
}
return nil, errors.New("Not found interface with ip : " + ip)
}
// GetIPAdress for get ip adress
func GetIPAdress(_interface *net.Interface) string {
var ip net.IP
ipv4 := ""
addrs, _ := _interface.Addrs()
for _, interfaceIP := range addrs {
switch v := interfaceIP.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip.To4() != nil {
ipv4 = ip.To4().String()
}
}
return ipv4
}