-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip.go
66 lines (57 loc) · 1.17 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
package main
import (
"fmt"
"strconv"
"strings"
)
// IP is IPv4 and IPv6 interface
type IP interface {
fmt.Stringer
Valid() (bool, error)
}
// IPv4 to contain IP-Adress
type IPv4 struct {
Adress []byte
Port int16
}
func (i IPv4) String() string {
return fmt.Sprintf("%d.%d.%d.%d:%d", i.Adress[0], i.Adress[1], i.Adress[2], i.Adress[3], i.Port)
}
// Valid checks if IP has valid form
func (i IPv4) Valid() (bool, error) {
var sum byte
for _, v := range i.Adress {
sum += v
}
return sum != 0, nil
}
func toIP(s string) (IP, error) {
spl := strings.Split(s+":", ":")
ins, err := splitIPstring(spl[0])
p, _ := strconv.ParseInt(spl[1], 10, 16)
iport := int16(p)
if iport < 1000 {
iport = port
}
return &IPv4{ins, iport}, err
}
func splitIPstring(s string) ([]byte, error) {
b := make([]byte, 4)
sarr := strings.Split(s, ".")
if len(sarr) != len(b) {
return b, IPerror(s + " is wrong format")
}
for k, v := range sarr {
n, err := strconv.ParseUint(v, 10, 8)
if err != nil || k == len(b) {
return b, err
}
b[k] = uint8(n)
}
return b, nil
}
// IPerror to be returned on format error
type IPerror string
func (e IPerror) Error() string {
return string(e)
}