/functions/network/ip2long.js

http://github.com/kvz/phpjs · JavaScript · 35 lines · 18 code · 0 blank · 17 comment · 11 complexity · 5bc25ad5b97fbcc52a5410c3bcb3b2e9 MD5 · raw file

  1. function ip2long (IP) {
  2. // http://kevin.vanzonneveld.net
  3. // + original by: Waldo Malqui Silva
  4. // + improved by: Victor
  5. // + revised by: fearphage (http://http/my.opera.com/fearphage/)
  6. // + revised by: Theriault
  7. // * example 1: ip2long('192.0.34.166');
  8. // * returns 1: 3221234342
  9. // * example 2: ip2long('0.0xABCDEF');
  10. // * returns 2: 11259375
  11. // * example 3: ip2long('255.255.255.256');
  12. // * returns 3: false
  13. var i = 0;
  14. // PHP allows decimal, octal, and hexadecimal IP components.
  15. // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
  16. IP = IP.match(/^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i); // Verify IP format.
  17. if (!IP) {
  18. return false; // Invalid format.
  19. }
  20. // Reuse IP variable for component counter.
  21. IP[0] = 0;
  22. for (i = 1; i < 5; i += 1) {
  23. IP[0] += !! ((IP[i] || '').length);
  24. IP[i] = parseInt(IP[i]) || 0;
  25. }
  26. // Continue to use IP for overflow values.
  27. // PHP does not allow any component to overflow.
  28. IP.push(256, 256, 256, 256);
  29. // Recalculate overflow of last component supplied to make up for missing components.
  30. IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]);
  31. if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) {
  32. return false;
  33. }
  34. return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1;
  35. }