-
Notifications
You must be signed in to change notification settings - Fork 19
/
gomap_funcs.go
81 lines (71 loc) · 1.87 KB
/
gomap_funcs.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
package gomap
import (
"encoding/binary"
"fmt"
"log"
"net"
"strings"
)
func canSocketBind(laddr string) bool {
// Check if user can listen on socket
listenAddr, err := net.ResolveIPAddr("ip4", laddr)
if err != nil {
return false
}
conn, err := net.ListenIP("ip4:tcp", listenAddr)
if err != nil {
return false
}
conn.Close()
return true
}
// createHostRange converts a input ip addr string to a slice of ips on the cidr
func createHostRange(netw string) []string {
_, ipv4Net, err := net.ParseCIDR(netw)
if err != nil {
log.Fatal(err)
}
mask := binary.BigEndian.Uint32(ipv4Net.Mask)
start := binary.BigEndian.Uint32(ipv4Net.IP)
finish := (start & mask) | (mask ^ 0xffffffff)
var hosts []string
for i := start + 1; i <= finish-1; i++ {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, i)
hosts = append(hosts, ip.String())
}
return hosts
}
// getLocalRange returns local ip range or defaults on error to most common
func getLocalRange() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "192.168.1.0/24"
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
split := strings.Split(ipnet.IP.String(), ".")
return split[0] + "." + split[1] + "." + split[2] + ".0/24"
}
}
}
return "192.168.1.0/24"
}
// getLocalRange returns local ip range or defaults on error to most common
func getLocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String(), err
}
}
}
return "", fmt.Errorf("No IP Found")
}