is-fast-ip.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Check if a hostname is an IP. You should be aware that this only works
  3. * because `hostname` is already garanteed to be a valid hostname!
  4. */
  5. export function isProbablyIpv4(hostname: string): boolean {
  6. // Cannot be shorted than 1.1.1.1 or longer than 255.255.255.255
  7. if (hostname.length < 7 || hostname.length > 15) {
  8. return false;
  9. }
  10. let numberOfDots = 0;
  11. for (let i = 0; i < hostname.length; i += 1) {
  12. const code = hostname.charCodeAt(i);
  13. if (code === 46 /* '.' */) {
  14. numberOfDots += 1;
  15. } else if (code < 48 /* '0' */ || code > 57 /* '9' */) {
  16. return false;
  17. }
  18. }
  19. return (
  20. numberOfDots === 3
  21. && hostname.charCodeAt(0) !== 46 /* '.' */
  22. && hostname.charCodeAt(hostname.length - 1) !== 46 /* '.' */
  23. );
  24. }
  25. export function isProbablyIpv6(hostname: string): boolean {
  26. if (hostname.length < 3) {
  27. return false;
  28. }
  29. let start = hostname[0] === '[' ? 1 : 0;
  30. let end = hostname.length;
  31. if (hostname[end - 1] === ']') {
  32. end -= 1;
  33. }
  34. // We only consider the maximum size of a normal IPV6. Note that this will
  35. // fail on so-called "IPv4 mapped IPv6 addresses" but this is a corner-case
  36. // and a proper validation library should be used for these.
  37. if (end - start > 39) {
  38. return false;
  39. }
  40. /* eslint-disable sukka/no-single-return -- here it goes */
  41. let hasColon = false;
  42. for (; start < end; start += 1) {
  43. const code = hostname.charCodeAt(start);
  44. if (code === 58 /* ':' */) {
  45. hasColon = true;
  46. } else if (
  47. !(
  48. (
  49. (code >= 48 && code <= 57) // 0-9
  50. || (code >= 97 && code <= 102) // a-f
  51. || (code >= 65 && code <= 90) // A-F
  52. )
  53. )
  54. ) {
  55. return false;
  56. }
  57. }
  58. return hasColon;
  59. /* eslint-enable sukka/no-single-return -- here it goes */
  60. }