IPv4.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace app\extra\ip2region\xdb;
  3. const IPv4VersionNo = 4;
  4. class IPv4
  5. {
  6. public $id;
  7. public $name;
  8. public $bytes;
  9. public $segmentIndexSize;
  10. private static $C = null;
  11. public static function default() {
  12. if (self::$C == null) {
  13. // 14 = 4 + 4 + 2 + 4
  14. self::$C = new self(IPv4VersionNo, 'IPv4', 4, 14);
  15. }
  16. return self::$C;
  17. }
  18. public function __construct($id, $name, $bytes, $segmentIndexSize) {
  19. $this->id = $id;
  20. $this->name = $name;
  21. $this->bytes = $bytes;
  22. $this->segmentIndexSize = $segmentIndexSize;
  23. }
  24. // compare the two ip bytes with the current version
  25. public function ipSubCompare($ip1, $buff, $offset) {
  26. // ip1: Little endian byte order encoded long from searcher.
  27. // ip2: Little endian byte order read from xdb index.
  28. $len = strlen($ip1);
  29. $eIdx = $offset + $len;
  30. for ($i = 0, $j = $eIdx - 1; $i < $len; $i++, $j--) {
  31. $i1 = ord($ip1[$i]) & 0xFF;
  32. $i2 = ord($buff[$j]) & 0xFF;
  33. // printf("i:%d, j:%d, i1:%d, i2:%d\n", $i, $j, $i1, $i2);
  34. if ($i1 > $i2) {
  35. return 1;
  36. } else if ($i1 < $i2) {
  37. return -1;
  38. }
  39. }
  40. return 0;
  41. }
  42. public function __toString() {
  43. return sprintf(
  44. "{id:%d, name:%s, bytes:%d, segmentIndexSize:%d}",
  45. $this->id, $this->name, $this->bytes, $this->segmentIndexSize
  46. );
  47. }
  48. }