-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipport.go
67 lines (59 loc) · 1.07 KB
/
ipport.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
package webutil
import (
"net"
"strconv"
"strings"
)
// ParseIPPort will parse an IP with optionally a port
func ParseIPPort(ip string) *net.TCPAddr {
if len(ip) < 2 {
// can't parse something that small
return nil
}
res := &net.TCPAddr{}
pos := strings.LastIndex(ip, ":") // is there a port?
if ip[0] == '[' {
ip_end := strings.Index(ip, "]")
if ip_end == -1 {
return nil
}
if ip_end != pos-1 {
res.IP = net.ParseIP(ip[1 : len(ip)-1])
if res.IP != nil {
return res
}
return nil // :(
}
res.IP = net.ParseIP(ip[1:ip_end])
if res.IP == nil {
return nil
}
ip = ip[pos:]
} else if pos > 0 {
res.IP = net.ParseIP(ip[0:pos])
if res.IP == nil {
res.IP = net.ParseIP(ip)
if res.IP != nil {
return res
}
return nil
}
ip = ip[pos:]
} else if pos == -1 {
res.IP = net.ParseIP(ip)
if res.IP == nil {
return nil
}
return res
}
// only remains is ":port"
if ip[0] != ':' {
return nil
}
port, err := strconv.ParseUint(ip[1:], 10, 16)
if err != nil {
return nil
}
res.Port = int(port)
return res
}