...
1package iphelper
2
3import (
4 "fmt"
5 "strconv"
6 "strings"
7)
8
9// endpoint, such as '1.1.1.1:53' or ipv6 or so
10// returns a network ip, a port, version (4 or 6)
11func ParseEndpoint(endpoint string) (string, uint32, int, error) {
12 if len(endpoint) < 4 {
13 return "", 0, 0, fmt.Errorf("\"%s\" is not a valid ip", endpoint)
14 }
15 ct := strings.Count(endpoint, ":")
16 if ct == 1 {
17 idx := strings.Index(endpoint, ":")
18 ip := endpoint[:idx]
19 port, err := strconv.Atoi(endpoint[idx+1:])
20 if err != nil {
21 return "", 0, 0, err
22 }
23 return ip, uint32(port), 4, nil
24 }
25
26 if ct == 0 {
27 return endpoint, 0, 4, nil
28 }
29
30 // must be ip6:
31 if endpoint[0] != '[' {
32 // without port
33 return endpoint, 0, 6, nil
34 }
35
36 ep := endpoint[1:]
37 idx := strings.Index(ep, "]")
38 if idx == -1 {
39 return "", 0, 0, fmt.Errorf("not a valid ipv6 with port: \"%s\"", endpoint)
40 }
41 ip := ep[:idx]
42 port, err := strconv.Atoi(ep[idx+2:]) // skip "]" and ":"
43 if err != nil {
44 return "", 0, 0, err
45 }
46 return ip, uint32(port), 6, nil
47}
View as plain text