-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
80 lines (73 loc) · 1.38 KB
/
ip.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
package host
import (
"bytes"
log "github.com/colt3k/nglog/ng"
"net"
)
// GetIPs looks at interfaces and returns list of comma separated ipv4 IPs
func GetIPs() string {
var ips bytes.Buffer
ifaces, err := net.Interfaces()
if err != nil {
log.Logf(log.ERROR, "%v", err)
}
// handle err
for _, i := range ifaces {
var addrs []net.Addr
addrs, err = i.Addrs()
if err != nil {
log.Logf(log.ERROR, "%v", err)
}
// handle err
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
if !v.IP.IsLoopback() {
if v.IP.To4() != nil {
ip = v.IP
}
}
case *net.IPAddr:
if !v.IP.IsLoopback() {
if v.IP.To4() != nil {
ip = v.IP
}
}
}
if ip != nil {
if ips.Len() > 0 {
ips.WriteString(",")
}
ips.WriteString(ip.String())
}
}
}
return ips.String()
}
// GetOutboundIP find IP address that sends publicly
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Logf(log.ERROR, "%v", err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
// FindIP find host IP address
func FindIP(host string) string {
ips := ""
addr, err := net.LookupIP(host)
if err != nil {
ips = "unknown"
} else {
for l, m := range addr {
if l > 0 {
ips += ", "
}
ips += m.String()
}
}
return ips
}