IpLocationService.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. namespace app\service;
  3. class IpLocationService
  4. {
  5. private $prefStart = [];
  6. private $prefEnd = [];
  7. private $endArr = [];
  8. private $fp;
  9. private $data;
  10. private static $instance = null;
  11. private $dataPath;
  12. private function __construct()
  13. {
  14. $this->dataPath = app()->getRootPath() . 'data/ipdatacloud.dat';
  15. $this->loadData();
  16. }
  17. private function loadData()
  18. {
  19. if (!file_exists($this->dataPath)) {
  20. throw new \Exception("IP数据文件不存在: {$this->dataPath}");
  21. }
  22. $this->fp = fopen($this->dataPath, 'rb');
  23. if (!$this->fp) {
  24. throw new \Exception("无法打开IP数据文件");
  25. }
  26. $fsize = filesize($this->dataPath);
  27. $this->data = fread($this->fp, $fsize);
  28. // 确保数据文件有足够的大小
  29. if (strlen($this->data) < 2052) {
  30. throw new \Exception("IP数据文件格式错误或损坏");
  31. }
  32. for ($k = 0; $k < 256; $k++) {
  33. $i = $k * 8 + 4;
  34. // 确保不会超出数据范围
  35. if ($i + 7 >= strlen($this->data)) {
  36. $this->prefStart[$k] = 0;
  37. $this->prefEnd[$k] = 0;
  38. continue;
  39. }
  40. $this->prefStart[$k] = $this->bytesToLong(
  41. $this->data[$i],
  42. $this->data[$i + 1],
  43. $this->data[$i + 2],
  44. $this->data[$i + 3]
  45. );
  46. $this->prefEnd[$k] = $this->bytesToLong(
  47. $this->data[$i + 4],
  48. $this->data[$i + 5],
  49. $this->data[$i + 6],
  50. $this->data[$i + 7]
  51. );
  52. }
  53. }
  54. public static function getInstance()
  55. {
  56. if (self::$instance === null) {
  57. self::$instance = new self();
  58. }
  59. return self::$instance;
  60. }
  61. public function getLocationFormatted($ip)
  62. {
  63. $result = $this->getLocation($ip);
  64. if (!$result['status']) {
  65. return $result;
  66. }
  67. // 解析IP位置信息
  68. // 格式:亚洲|中国|广东|广州|荔湾|电信|440100|China|CN|113.2442|23.12592|18|510000|020|CHXX0037|AS4134
  69. $location = $result['data']['location'];
  70. $info = explode('|', $location);
  71. return [
  72. 'status' => true,
  73. 'message' => 'success',
  74. 'data' => [
  75. 'ip' => $ip,
  76. 'continent' => isset($info[0]) ? $info[0] : '',
  77. 'country' => isset($info[1]) ? $info[1] : '',
  78. 'province' => isset($info[2]) ? $info[2] : '',
  79. 'city' => isset($info[3]) ? $info[3] : '',
  80. 'district' => isset($info[4]) ? $info[4] : '',
  81. 'isp' => isset($info[5]) ? $info[5] : '',
  82. 'area_code' => isset($info[6]) ? $info[6] : '',
  83. 'country_en' => isset($info[7]) ? $info[7] : '',
  84. 'country_code' => isset($info[8]) ? $info[8] : '',
  85. 'longitude' => isset($info[9]) ? $info[9] : '',
  86. 'latitude' => isset($info[10]) ? $info[10] : '',
  87. 'altitude' => isset($info[11]) ? $info[11] : '',
  88. 'zip_code' => isset($info[12]) ? $info[12] : '',
  89. 'city_code' => isset($info[13]) ? $info[13] : '',
  90. 'weather_station' => isset($info[14]) ? $info[14] : '',
  91. 'asn' => isset($info[15]) ? $info[15] : ''
  92. ]
  93. ];
  94. }
  95. public function batchGetLocationFormatted(array $ips)
  96. {
  97. $results = [];
  98. foreach ($ips as $ip) {
  99. $results[$ip] = $this->getLocationFormatted($ip);
  100. }
  101. return $results;
  102. }
  103. public function getLocation($ip)
  104. {
  105. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  106. return [
  107. 'status' => false,
  108. 'message' => '无效的IP地址格式',
  109. 'data' => null
  110. ];
  111. }
  112. try {
  113. $val = sprintf("%u", ip2long($ip));
  114. $ipArr = explode('.', $ip);
  115. $pref = intval($ipArr[0]);
  116. // 确保前缀索引在有效范围内
  117. if (!isset($this->prefStart[$pref]) || !isset($this->prefEnd[$pref])) {
  118. return [
  119. 'status' => false,
  120. 'message' => '无IP信息',
  121. 'data' => null
  122. ];
  123. }
  124. $low = $this->prefStart[$pref];
  125. $high = $this->prefEnd[$pref];
  126. $cur = ($low == $high) ? $low : $this->search($low, $high, $val);
  127. if ($cur == 100000000) {
  128. return [
  129. 'status' => false,
  130. 'message' => '无IP信息',
  131. 'data' => null
  132. ];
  133. }
  134. $location = $this->getByCur($cur);
  135. return [
  136. 'status' => true,
  137. 'message' => 'success',
  138. 'data' => [
  139. 'ip' => $ip,
  140. 'location' => $location
  141. ]
  142. ];
  143. } catch (\Exception $e) {
  144. return [
  145. 'status' => false,
  146. 'message' => '查询失败: ' . $e->getMessage(),
  147. 'data' => null
  148. ];
  149. }
  150. }
  151. public function batchGetLocation(array $ips)
  152. {
  153. $results = [];
  154. foreach ($ips as $ip) {
  155. $results[$ip] = $this->getLocation($ip);
  156. }
  157. return $results;
  158. }
  159. private function getByCur($i)
  160. {
  161. $p = intval(2052 + (intval($i) * 9));
  162. // 确保偏移量不超出数据范围
  163. if ($p + 8 >= strlen($this->data)) {
  164. return "无信息";
  165. }
  166. $offset = $this->bytesToLong(
  167. $this->data[4 + $p],
  168. $this->data[5 + $p],
  169. $this->data[6 + $p],
  170. $this->data[7 + $p]
  171. );
  172. $length = ord($this->data[8 + $p]);
  173. // 确保读取范围有效
  174. if ($offset + $length > strlen($this->data)) {
  175. return "无信息";
  176. }
  177. return substr($this->data, $offset, $length);
  178. }
  179. private function search($low, $high, $k)
  180. {
  181. $M = 0;
  182. while ($low <= $high) {
  183. $mid = intval(floor(($low + $high) / 2));
  184. $p = intval(2052 + ($mid * 9));
  185. // 确保偏移量不超出数据范围
  186. if ($p + 3 >= strlen($this->data)) {
  187. break;
  188. }
  189. $endipNum = $this->bytesToLong(
  190. $this->data[$p],
  191. $this->data[$p + 1],
  192. $this->data[$p + 2],
  193. $this->data[$p + 3]
  194. );
  195. if ($endipNum >= $k) {
  196. $M = $mid;
  197. if ($mid == 0) {
  198. break;
  199. }
  200. $high = $mid - 1;
  201. } else {
  202. $low = $mid + 1;
  203. }
  204. }
  205. return $M;
  206. }
  207. private function bytesToLong($a, $b, $c, $d)
  208. {
  209. $iplong = (ord($a) << 0) | (ord($b) << 8) | (ord($c) << 16) | (ord($d) << 24);
  210. if ($iplong < 0) {
  211. $iplong += 4294967296;
  212. }
  213. return $iplong;
  214. }
  215. public function __destruct()
  216. {
  217. if ($this->fp !== null) {
  218. fclose($this->fp);
  219. }
  220. }
  221. }