diff options
-rw-r--r-- | util/ip.go | 22 |
1 files changed, 15 insertions, 7 deletions
@@ -5,10 +5,14 @@ import ( | |||
5 | "regexp" | 5 | "regexp" |
6 | ) | 6 | ) |
7 | 7 | ||
8 | // Parses an IPv4 or IPv6 address with an optional port on the end. Returns | 8 | // Matches: |
9 | // match groups for the addresses. The first match is the IPv6 address and the | 9 | // - IPv4: 192.168.1.1 |
10 | // second the IPv4 address. | 10 | // - IPv4 + Port: 192.168.1.1:2020 |
11 | var ipRegexp = regexp.MustCompile(`(?:\[([0-9a-f:]+)\]|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(?::\d+)?`) | 11 | // - IPv6 + Port: [fe80::551f:5aff:49cf:13e4]:2020 |
12 | // - IPv6: fe80::551f:5aff:49cf:13e4 | ||
13 | // | ||
14 | // Return Order: []string{matched, IPv4, IPv6 (port notation), IPv6 (raw notation), Port | ||
15 | var ipRegexp = regexp.MustCompile(`(?:((?:\d+\.){3}\d+)|\[([^\]]+)\]|([0-9a-f:]+))(?::(\d+))?`) | ||
12 | 16 | ||
13 | func ParseIP(s string) net.IP { | 17 | func ParseIP(s string) net.IP { |
14 | ips := ipRegexp.FindStringSubmatch(s) | 18 | ips := ipRegexp.FindStringSubmatch(s) |
@@ -16,9 +20,13 @@ func ParseIP(s string) net.IP { | |||
16 | return nil | 20 | return nil |
17 | } | 21 | } |
18 | 22 | ||
19 | if v6, v4 := ips[1], ips[2]; v6 != "" { | 23 | if ips[1] != "" { |
20 | return net.ParseIP(v6) | 24 | return net.ParseIP(ips[1]) |
25 | } else if ips[2] != "" { | ||
26 | return net.ParseIP(ips[2]) | ||
27 | } else if ips[3] != "" { | ||
28 | return net.ParseIP(ips[3]) | ||
21 | } else { | 29 | } else { |
22 | return net.ParseIP(v4) | 30 | return nil |
23 | } | 31 | } |
24 | } | 32 | } |