ip_address.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package util
  2. import (
  3. "net"
  4. "strings"
  5. )
  6. // ParseIPAddress parses an IP address and removes port and/or IPV6 format
  7. func ParseIPAddress(input string) string {
  8. host, _ := SplitHostPort(input)
  9. ip := net.ParseIP(host)
  10. if ip == nil {
  11. return host
  12. }
  13. if ip.IsLoopback() {
  14. return "127.0.0.1"
  15. }
  16. return ip.String()
  17. }
  18. // SplitHostPortDefault splits ip address/hostname string by host and port. Defaults used if no match found
  19. func SplitHostPortDefault(input, defaultHost, defaultPort string) (host string, port string) {
  20. port = defaultPort
  21. s := input
  22. lastIndex := strings.LastIndex(input, ":")
  23. if lastIndex != -1 {
  24. if lastIndex > 0 && input[lastIndex-1:lastIndex] != ":" {
  25. s = input[:lastIndex]
  26. port = input[lastIndex+1:]
  27. } else if lastIndex == 0 {
  28. s = defaultHost
  29. port = input[lastIndex+1:]
  30. }
  31. } else {
  32. port = defaultPort
  33. }
  34. s = strings.Replace(s, "[", "", -1)
  35. s = strings.Replace(s, "]", "", -1)
  36. port = strings.Replace(port, "[", "", -1)
  37. port = strings.Replace(port, "]", "", -1)
  38. return s, port
  39. }
  40. // SplitHostPort splits ip address/hostname string by host and port
  41. func SplitHostPort(input string) (host string, port string) {
  42. return SplitHostPortDefault(input, "", "")
  43. }