-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
ipChecking.go
74 lines (65 loc) · 1.41 KB
/
ipChecking.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
package ipchecking
import (
"fmt"
"log"
"net"
"os"
"strings"
)
var (
// Logger ip checking logger
Logger = log.New(os.Stdout, "IPChecking: ", log.Ldate|log.Ltime|log.Lshortfile)
)
// IP struct that holds an IP Addr
type IP struct {
Net *net.IPNet
}
// StrToIP convert ip string array to ip struct array
func StrToIP(iplist []string) ([]IP, error) {
rlist := []IP{}
for _, v := range iplist {
ip, err := BuildIP(v)
if err != nil {
Logger.Printf("Error: %s not valid", v)
continue
}
rlist = append(rlist, ip)
}
return rlist, nil
}
func isIPv4(ip string) bool {
return strings.Contains(ip, ".")
}
// BuildIP Parse a string to extract the IP
func BuildIP(ip string) (IP, error) {
var res IP
var err error
tmpSubnet := strings.Split(ip, "/")
if len(tmpSubnet) == 1 {
tempIP := net.ParseIP(ip)
if tempIP == nil {
Logger.Printf("%s is not a valid IP or IP/Net", ip)
return res, fmt.Errorf("%s is not a valid IP or IP/Net", ip)
}
if isIPv4(ip) {
ip = ip + "/32"
} else {
ip = ip + "/128"
}
}
_, ipNet, err := net.ParseCIDR(ip)
if err != nil {
Logger.Printf("%e", err)
return res, err
}
res.Net = ipNet
return res, nil
}
// ToString convert IP struct to string
func (ip IP) ToString() string {
return ip.Net.String()
}
// CheckIPInSubnet Check is the IP Is the same or in the same subnet
func (ip IP) CheckIPInSubnet(i string) bool {
return ip.Net.Contains(net.ParseIP(i))
}