...
1
18
19 package utils
20
21 import (
22 "discovery/log"
23 "net"
24 "strings"
25 )
26
27 type IPError struct{}
28
29 func (e IPError) Error() string {
30 return "Could not get ip address"
31 }
32
33 func GetInternalIP(ifaceName string) (string, error) {
34 iface, err := net.InterfaceByName(ifaceName)
35 if err != nil {
36 log.Log.Errorf("Could not find interface \"%s\"", ifaceName)
37 return "", IPError{}
38 }
39 if iface.Flags&net.FlagUp == 0 {
40 log.Log.Errorf("Interface \"%s\" is down", ifaceName)
41 return "", IPError{}
42 }
43 if iface.Flags&net.FlagLoopback != 0 {
44 log.Log.Errorf("Interface \"%s\" is loopback", ifaceName)
45 return "", IPError{}
46 }
47
48 addresses, err := iface.Addrs()
49
50 for _, addr := range addresses {
51 var ip net.IP
52 switch v := addr.(type) {
53 case *net.IPNet:
54 ip = v.IP
55 case *net.IPAddr:
56 ip = v.IP
57 }
58 if ip == nil || ip.IsLoopback() {
59 continue
60 }
61 ip = ip.To4()
62 if ip == nil {
63 continue
64 }
65 return ip.String(), nil
66 }
67
68 log.Log.Errorf("Could not get ip for \"%s\"", ifaceName)
69 return "", IPError{}
70 }
71
72
75
76 func IsolateIPFromPort(ip string) string {
77 lastColon := strings.LastIndex(ip, ":")
78 if lastColon == -1 {
79 return ip
80 }
81 trueIp := ip[0:lastColon]
82 return trueIp
83 }
84
View as plain text