NetworkDetection.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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(
  25. "【" . $checkName . "阻断检测】检测" . $ip . "时,接口返回异常访问链接:" . $url
  26. );
  27. return false;
  28. }
  29. if ( ! $result['success']) {
  30. if ($result['error'] === "execute timeout (3s)") {
  31. sleep(10);
  32. return self::networkCheck($ip, $type, $port);
  33. }
  34. Log::warning(
  35. "【" . $checkName . "阻断检测】检测" . $ip . ($port ?: '') . "时,返回" . var_export(
  36. $result,
  37. true
  38. )
  39. );
  40. return false;
  41. }
  42. if ($result['firewall-enable'] && $result['firewall-disable']) {
  43. return "通讯正常"; // 正常
  44. }
  45. if ($result['firewall-enable'] && ! $result['firewall-disable']) {
  46. return "海外阻断"; // 国外访问异常
  47. }
  48. if ( ! $result['firewall-enable'] && $result['firewall-disable']) {
  49. return "国内阻断"; // 被墙
  50. }
  51. return "机器宕机"; // 服务器宕机
  52. }
  53. return false;
  54. }
  55. /**
  56. * 用外部API进行Ping检测
  57. *
  58. * @param string $ip 被检测的IP或者域名
  59. *
  60. * @return bool|array
  61. */
  62. public static function ping(string $ip)
  63. {
  64. $url = 'https://api.oioweb.cn/api/hostping.php?host=' . $ip;//https://api.iiwl.cc/api/ping.php?host=
  65. $request = (new Client(['timeout' => 15]))->get($url);
  66. $message = json_decode($request->getBody(), true);
  67. // 发送成功
  68. if ($request->getStatusCode() == 200) {
  69. if ($message && $message['code']) {
  70. return $message['data'];
  71. }
  72. // 发送失败
  73. Log::warning(
  74. "【PING】检测" . $ip . "时,返回" . var_export($message, true)
  75. );
  76. return false;
  77. }
  78. Log::warning("【PING】检测" . $ip . "时,接口返回异常访问链接:" . $url);
  79. // 发送错误
  80. return false;
  81. }
  82. }