utils.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package utils
  2. import "net"
  3. func isValidIP(ip string) bool {
  4. return net.ParseIP(ip) != nil
  5. }
  6. func IsAlphaNumeric(c byte) bool {
  7. return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'
  8. }
  9. //This function is lifted from go source
  10. //See https://github.com/golang/go/blob/master/src/net/dnsclient.go#L75
  11. func isValidHostname(s string) bool {
  12. // The root domain name is valid. See golang.org/issue/45715.
  13. if s == "." {
  14. return true
  15. }
  16. // See RFC 1035, RFC 3696.
  17. // Presentation format has dots before every label except the first, and the
  18. // terminal empty label is optional here because we assume fully-qualified
  19. // (absolute) input. We must therefore reserve space for the first and last
  20. // labels' length octets in wire format, where they are necessary and the
  21. // maximum total length is 255.
  22. // So our _effective_ maximum is 253, but 254 is not rejected if the last
  23. // character is a dot.
  24. l := len(s)
  25. if l == 0 || l > 254 || l == 254 && s[l-1] != '.' {
  26. return false
  27. }
  28. last := byte('.')
  29. nonNumeric := false // true once we've seen a letter or hyphen
  30. partlen := 0
  31. for i := 0; i < len(s); i++ {
  32. c := s[i]
  33. switch {
  34. default:
  35. return false
  36. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
  37. nonNumeric = true
  38. partlen++
  39. case '0' <= c && c <= '9':
  40. // fine
  41. partlen++
  42. case c == '-':
  43. // Byte before dash cannot be dot.
  44. if last == '.' {
  45. return false
  46. }
  47. partlen++
  48. nonNumeric = true
  49. case c == '.':
  50. // Byte before dot cannot be dot, dash.
  51. if last == '.' || last == '-' {
  52. return false
  53. }
  54. if partlen > 63 || partlen == 0 {
  55. return false
  56. }
  57. partlen = 0
  58. }
  59. last = c
  60. }
  61. if last == '-' || partlen > 63 {
  62. return false
  63. }
  64. return nonNumeric
  65. }
  66. func IsValidHostnameOrIP(hostname string) bool {
  67. return isValidIP(hostname) || isValidHostname(hostname)
  68. }