-
Notifications
You must be signed in to change notification settings - Fork 3
/
host.go
131 lines (102 loc) · 2.53 KB
/
host.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// Copyright 2015 Eryx <evorui аt gmаil dοt cοm>, All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package inapi
import (
"errors"
"fmt"
"net"
"strconv"
"strings"
)
// default: 127.0.0.1:9529
type HostNodeAddress string
type HostNodeAddresses []HostNodeAddress
func (addr HostNodeAddress) String() string {
return string(addr)
}
func (addr HostNodeAddress) Valid() bool {
if addr.Port() < 1 {
return false
}
if v := net.ParseIP(addr.IP()); v == nil || len(v) != 16 {
return false
}
return true
}
func (addr HostNodeAddress) IP() string {
if pos := strings.LastIndex(string(addr), ":"); pos > 0 {
return string(addr)[:pos]
}
return string(addr)
}
func (addr HostNodeAddress) Port() uint16 {
if pos := strings.LastIndex(string(addr), ":"); pos > 0 {
port, _ := strconv.Atoi(string(addr)[pos+1:])
return uint16(port)
}
return 0
}
func (addr *HostNodeAddress) SetIP(ip string) error {
if addr.Port() > 0 {
*addr = HostNodeAddress(fmt.Sprintf("%s:%d", ip, addr.Port()))
} else {
*addr = HostNodeAddress(ip)
}
return nil
}
func (addr *HostNodeAddress) SetPort(port uint16) error {
if (*addr).IP() != "" {
*addr = HostNodeAddress(fmt.Sprintf("%s:%d", addr.IP(), port))
} else {
*addr = HostNodeAddress(fmt.Sprintf(":%d", port))
}
return nil
}
func (it HostNodeAddresses) Equal(it2 HostNodeAddresses) bool {
if len(it) == len(it2) {
for _, v := range it {
found := false
for _, v2 := range it2 {
if v == v2 {
found = true
break
}
}
if !found {
return false
}
}
return true
}
return false
}
func PrivateIPValid(ipAddr string) error {
// Private IPv4
// 10.0.0.0 ~ 10.255.255.255
// 172.16.0.0 ~ 172.31.255.255
// 192.168.0.0 ~ 192.168.255.255
ip := net.ParseIP(ipAddr)
if ip == nil {
return errors.New("invalid ip address")
}
ip = ip.To4()
ipa := int(ip[0])
ipb := int(ip[1])
if ipa == 10 ||
(ipa == 172 && ipb >= 16 && ipb <= 31) ||
(ipa == 192 && ipb == 168) {
return nil
}
return errors.New("invalid private ip address")
}