...

Source file src/k8s.io/kubernetes/pkg/proxy/util/endpoints.go

Documentation: k8s.io/kubernetes/pkg/proxy/util

     1  /*
     2  Copyright 2017 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"net"
    21  	"strconv"
    22  
    23  	"k8s.io/klog/v2"
    24  	netutils "k8s.io/utils/net"
    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.
    30  func IPPart(s string) string {
    31  	if ip := netutils.ParseIPSloppy(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.ErrorS(err, "Failed to parse host-port", "input", s)
    39  		return ""
    40  	}
    41  	// Check if host string is a valid IP address
    42  	ip := netutils.ParseIPSloppy(host)
    43  	if ip == nil {
    44  		klog.ErrorS(nil, "Failed to parse IP", "input", host)
    45  		return ""
    46  	}
    47  	return ip.String()
    48  }
    49  
    50  // PortPart returns just the port part of an endpoint string.
    51  func PortPart(s string) (int, error) {
    52  	// Must be IP:port
    53  	_, port, err := net.SplitHostPort(s)
    54  	if err != nil {
    55  		klog.ErrorS(err, "Failed to parse host-port", "input", s)
    56  		return -1, err
    57  	}
    58  	portNumber, err := strconv.Atoi(port)
    59  	if err != nil {
    60  		klog.ErrorS(err, "Failed to parse port", "input", port)
    61  		return -1, err
    62  	}
    63  	return portNumber, nil
    64  }
    65  

View as plain text