NetworkDetection.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Components;
  3. use Cache;
  4. use Http;
  5. use Log;
  6. class NetworkDetection
  7. {
  8. /**
  9. * 用api.50network.com进行节点阻断检测.
  10. *
  11. * @param string $ip 被检测的IP
  12. * @param bool $type TRUE 为ICMP,FALSE 为tcp
  13. * @param int|null $port 检测端口,默认为空
  14. *
  15. * @return bool|string
  16. */
  17. public static function networkCheck(string $ip, bool $type, $port = null)
  18. {
  19. $cacheKey = 'network_times_'.md5($ip);
  20. if (Cache::has($cacheKey)) {
  21. Cache::decrement($cacheKey);
  22. } else {
  23. Cache::put($cacheKey, 2, Day); // 24小时
  24. }
  25. $url = 'https://api.50network.com/china-firewall/check/ip/'.($type ? 'icmp/' : ($port ? 'tcp_port/' : 'tcp_ack/')).$ip.($port ? '/'.$port : '');
  26. $checkName = $type ? 'ICMP' : 'TCP';
  27. $response = Http::timeout(15)->get($url);
  28. if ($response->ok()) {
  29. $message = $response->json();
  30. if (! $message) {
  31. Log::warning('【'.$checkName.'阻断检测】检测'.$ip.'时,接口返回异常访问链接:'.$url);
  32. return false;
  33. }
  34. if (! $message['success']) {
  35. if ($message['error'] === 'execute timeout (3s)') {
  36. sleep(10);
  37. if (Cache::get($cacheKey) < 0) {
  38. Log::warning('【'.$checkName.'阻断检测】检测'.$ip.$port.'时,重复请求后无结果,最后返回'.$message['error']);
  39. return false;
  40. }
  41. return self::networkCheck($ip, $type, $port);
  42. }
  43. Log::warning('【'.$checkName.'阻断检测】检测'.$ip.$port.'时,返回'.var_export($message, true));
  44. return false;
  45. }
  46. if ($message['firewall-enable'] && $message['firewall-disable']) {
  47. return '通讯正常'; // 正常
  48. }
  49. if ($message['firewall-enable'] && ! $message['firewall-disable']) {
  50. return '海外阻断'; // 国外访问异常
  51. }
  52. if (! $message['firewall-enable'] && $message['firewall-disable']) {
  53. return '国内阻断'; // 被墙
  54. }
  55. return '机器宕机'; // 服务器宕机
  56. }
  57. return false;
  58. }
  59. /**
  60. * 用外部API进行Ping检测.
  61. *
  62. * @param string $ip 被检测的IP或者域名
  63. *
  64. * @return bool|array
  65. */
  66. public static function ping(string $ip)
  67. {
  68. $url = 'https://api.oioweb.cn/api/hostping.php?host='.$ip; // https://api.iiwl.cc/api/ping.php?host=
  69. $response = Http::timeout(15)->retry(2)->get($url);
  70. // 发送成功
  71. if ($response->ok()) {
  72. $message = $response->json();
  73. if ($message && $message['code']) {
  74. return $message['data'];
  75. }
  76. // 发送失败
  77. Log::warning('【PING】检测'.$ip.'时,返回'.var_export($message, true));
  78. return false;
  79. }
  80. Log::warning('【PING】检测'.$ip.'时,接口返回异常访问链接:'.$url);
  81. // 发送错误
  82. return false;
  83. }
  84. }