1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package util
18
19import (
20	"fmt"
21	"net"
22	"strconv"
23
24	"k8s.io/klog/v2"
25)
26
27// IPPart returns just the IP part of an IP or IP:port or endpoint string. If the IP
28// part is an IPv6 address enclosed in brackets (e.g. "[fd00:1::5]:9999"),
29// then the brackets are stripped as well.
30func IPPart(s string) string {
31	if ip := net.ParseIP(s); ip != nil {
32		// IP address without port
33		return s
34	}
35	// Must be IP:port
36	host, _, err := net.SplitHostPort(s)
37	if err != nil {
38		klog.Errorf("Error parsing '%s': %v", s, err)
39		return ""
40	}
41	// Check if host string is a valid IP address
42	ip := net.ParseIP(host)
43	if ip == nil {
44		klog.Errorf("invalid IP part '%s'", host)
45		return ""
46	}
47	return ip.String()
48}
49
50// PortPart returns just the port part of an endpoint string.
51func PortPart(s string) (int, error) {
52	// Must be IP:port
53	_, port, err := net.SplitHostPort(s)
54	if err != nil {
55		klog.Errorf("Error parsing '%s': %v", s, err)
56		return -1, err
57	}
58	portNumber, err := strconv.Atoi(port)
59	if err != nil {
60		klog.Errorf("Error parsing '%s': %v", port, err)
61		return -1, err
62	}
63	return portNumber, nil
64}
65
66// ToCIDR returns a host address of the form <ip-address>/32 for
67// IPv4 and <ip-address>/128 for IPv6
68func ToCIDR(ip net.IP) string {
69	len := 32
70	if ip.To4() == nil {
71		len = 128
72	}
73	return fmt.Sprintf("%s/%d", ip.String(), len)
74}
75