-
Notifications
You must be signed in to change notification settings - Fork 2
/
net_func.go
58 lines (50 loc) · 1.19 KB
/
net_func.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
package main
import (
"log"
"net"
)
func dupIP(ip net.IP) net.IP {
dup := make(net.IP, len(ip))
copy(dup, ip)
return dup
}
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
func NetGetNetworkIPs() (ip []net.IP, err error) {
var ipList []net.IP
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
// scan all interfaces
for _, iface := range ifaces {
if iface.Flags&net.FlagUp != 0 && iface.Flags&net.FlagBroadcast != 0 {
addrs, err := iface.Addrs()
if err != nil {
log.Printf("Error reading interface address %v : %v", iface, err)
} else {
for _, addr := range addrs {
ip, ipnet, err := net.ParseCIDR(addr.String())
if err != nil {
log.Printf("Error parsing CIDR %s : %v", addr.String(), err)
} else {
ip = ip.To4() // make sure that the IP is IPv4
if ip != nil { // will be nill if IPv6
log.Printf("Scanning network interface '%v' with CIDR = %v, IP = %v\n", iface.Name, addr.String(), ip)
for xip := ip.Mask(ipnet.Mask); ipnet.Contains(xip); inc(xip) {
ipList = append(ipList, dupIP(xip))
}
}
}
}
}
}
}
return ipList, nil
}