Files
grafana/pkg/util/ip_address.go
T

90 lines
2.0 KiB
Go
Raw Normal View History

2019-01-15 11:11:32 +01:00
package util
import (
2019-10-09 08:58:45 +02:00
"fmt"
2019-01-15 11:11:32 +01:00
"net"
"strings"
2019-10-09 08:58:45 +02:00
"github.com/grafana/grafana/pkg/util/errutil"
2019-01-15 11:11:32 +01:00
)
// ParseIPAddress parses an IP address and removes port and/or IPV6 format
2019-10-09 08:58:45 +02:00
func ParseIPAddress(input string) (string, error) {
addr, err := SplitHostPort(input)
if err != nil {
return "", errutil.Wrapf(err, "Failed to split network address '%s' by host and port",
input)
}
2019-02-04 13:10:32 +01:00
2019-10-09 08:58:45 +02:00
ip := net.ParseIP(addr.Host)
2019-02-04 13:10:32 +01:00
if ip == nil {
2019-10-09 08:58:45 +02:00
return addr.Host, nil
2019-02-04 13:10:32 +01:00
}
if ip.IsLoopback() {
2019-10-09 08:58:45 +02:00
if strings.Contains(addr.Host, ":") {
// IPv6
return "::1", nil
}
return "127.0.0.1", nil
2019-02-04 13:10:32 +01:00
}
2019-10-09 08:58:45 +02:00
return ip.String(), nil
}
type NetworkAddress struct {
Host string
Port string
2019-02-04 13:10:32 +01:00
}
// SplitHostPortDefault splits ip address/hostname string by host and port. Defaults used if no match found
2019-10-09 08:58:45 +02:00
func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddress, error) {
addr := NetworkAddress{
Host: defaultHost,
Port: defaultPort,
}
if len(input) == 0 {
return addr, nil
2019-10-09 08:58:45 +02:00
}
start := 0
// Determine if IPv6 address, in which case IP address will be enclosed in square brackets
if strings.Index(input, "[") == 0 {
addrEnd := strings.LastIndex(input, "]")
if addrEnd < 0 {
// Malformed address
return addr, fmt.Errorf("Malformed IPv6 address: '%s'", input)
2019-01-21 09:13:55 +01:00
}
2019-10-09 08:58:45 +02:00
start = addrEnd
}
if strings.LastIndex(input[start:], ":") < 0 {
// There's no port section of the input
// It's still useful to call net.SplitHostPort though, since it removes IPv6
// square brackets from the address
input = fmt.Sprintf("%s:%s", input, defaultPort)
2019-01-15 11:11:32 +01:00
}
2019-10-09 08:58:45 +02:00
host, port, err := net.SplitHostPort(input)
if err != nil {
return addr, errutil.Wrapf(err, "net.SplitHostPort failed for '%s'", input)
}
if len(host) > 0 {
addr.Host = host
}
if len(port) > 0 {
addr.Port = port
}
2019-01-15 11:11:32 +01:00
2019-10-09 08:58:45 +02:00
return addr, nil
2019-02-04 13:10:32 +01:00
}
2019-01-15 11:11:32 +01:00
2019-02-04 13:10:32 +01:00
// SplitHostPort splits ip address/hostname string by host and port
2019-10-09 08:58:45 +02:00
func SplitHostPort(input string) (NetworkAddress, error) {
if len(input) == 0 {
return NetworkAddress{}, fmt.Errorf("Input is empty")
}
2019-02-04 13:10:32 +01:00
return SplitHostPortDefault(input, "", "")
2019-01-15 11:11:32 +01:00
}