isIPRange.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import assertString from './util/assertString';
  2. import isIP from './isIP';
  3. var subnetMaybe = /^\d{1,3}$/;
  4. var v4Subnet = 32;
  5. var v6Subnet = 128;
  6. export default function isIPRange(str) {
  7. var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  8. assertString(str);
  9. var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet
  10. if (parts.length !== 2) {
  11. return false;
  12. }
  13. if (!subnetMaybe.test(parts[1])) {
  14. return false;
  15. } // Disallow preceding 0 i.e. 01, 02, ...
  16. if (parts[1].length > 1 && parts[1].startsWith('0')) {
  17. return false;
  18. }
  19. var isValidIP = isIP(parts[0], version);
  20. if (!isValidIP) {
  21. return false;
  22. } // Define valid subnet according to IP's version
  23. var expectedSubnet = null;
  24. switch (String(version)) {
  25. case '4':
  26. expectedSubnet = v4Subnet;
  27. break;
  28. case '6':
  29. expectedSubnet = v6Subnet;
  30. break;
  31. default:
  32. expectedSubnet = isIP(parts[0], '6') ? v6Subnet : v4Subnet;
  33. }
  34. return parts[1] <= expectedSubnet && parts[1] >= 0;
  35. }