NetworkDetection.php 2.3 KB

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