NetworkDetection.php 2.8 KB

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