NetworkDetection.php 2.3 KB

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