is-fast-ip.ts 813 B

123456789101112131415161718192021222324252627282930313233
  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
  7. if (hostname.length < 7) {
  8. return false;
  9. }
  10. // Cannot be longer than: 255.255.255.255
  11. if (hostname.length > 15) {
  12. return false;
  13. }
  14. let numberOfDots = 0;
  15. for (let i = 0; i < hostname.length; i += 1) {
  16. const code = hostname.charCodeAt(i);
  17. if (code === 46 /* '.' */) {
  18. numberOfDots += 1;
  19. } else if (code < 48 /* '0' */ || code > 57 /* '9' */) {
  20. return false;
  21. }
  22. }
  23. return (
  24. numberOfDots === 3
  25. && hostname.charCodeAt(0) !== 46
  26. && /* '.' */ hostname.charCodeAt(hostname.length - 1) !== 46 /* '.' */
  27. );
  28. }