endpoints.go 1.8 KB

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