summaryrefslogtreecommitdiff
path: root/util/ip.go
blob: 239973a6e83ce0a74e2226c58f5bd22b7d2e9bc1 (plain)
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
package util

import (
	"net"
	"regexp"
)

// Matches:
//  - IPv4: 192.168.1.1
//  - IPv4 + Port: 192.168.1.1:2020
//  - IPv6 + Port: [fe80::551f:5aff:49cf:13e4]:2020
//  - IPv6: fe80::551f:5aff:49cf:13e4
//
// Return Order: []string{matched, IPv4, IPv6 (port notation), IPv6 (raw notation), Port
var ipRegexp = regexp.MustCompile(`(?:((?:\d+\.){3}\d+)|\[([^\]]+)\]|([0-9a-f:]+))(?::(\d+))?`)

func ParseIP(s string) net.IP {
	ips := ipRegexp.FindStringSubmatch(s)
	if ips == nil {
		return nil
	}

	if ips[1] != "" {
		return net.ParseIP(ips[1])
	} else if ips[2] != "" {
		return net.ParseIP(ips[2])
	} else if ips[3] != "" {
		return net.ParseIP(ips[3])
	} else {
		return nil
	}
}