NetworkDetection.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Components;
  3. use Exception;
  4. use Log;
  5. class NetworkDetection
  6. {
  7. /**
  8. * 用api.50network.com进行节点阻断检测
  9. *
  10. * @param string $ip 被检测的IP
  11. * @param boolean $type TRUE 为ICMP,FALSE 为tcp
  12. * @param int $port 检测端口,默认为空
  13. *
  14. * @return bool|string
  15. */
  16. public static function networkCheck($ip, $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. try{
  21. $ret = json_decode(Curl::send($url), TRUE);
  22. if(!$ret){
  23. Log::warning("【".$checkName."阻断检测】检测".$ip."时,接口返回异常访问链接:".$url);
  24. return FALSE;
  25. }elseif(!$ret['success']){
  26. if($ret['error'] == "execute timeout (3s)"){
  27. sleep(10);
  28. return self::networkCheck($ip, $type, $port);
  29. }else{
  30. Log::warning("【".$checkName."阻断检测】检测".$ip.($port? : '')."时,返回".json_encode($ret));
  31. }
  32. return FALSE;
  33. }
  34. }catch(Exception $e){
  35. Log::warning("【".$checkName."阻断检测】检测".$ip."时,接口请求超时".$e);
  36. return FALSE;
  37. }
  38. if($ret['firewall-enable'] && $ret['firewall-disable']){
  39. return "通讯正常"; // 正常
  40. }elseif($ret['firewall-enable'] && !$ret['firewall-disable']){
  41. return "海外阻断"; // 国外访问异常
  42. }elseif(!$ret['firewall-enable'] && $ret['firewall-disable']){
  43. return "国内阻断"; // 被墙
  44. }else{
  45. return "机器宕机"; // 服务器宕机
  46. }
  47. }
  48. /**
  49. * 用api.iiwl.cc进行Ping检测
  50. *
  51. * @param string $ip 被检测的IP或者域名
  52. *
  53. * @return bool|array
  54. */
  55. public static function ping($ip)
  56. {
  57. $url = 'https://api.iiwl.cc/api/ping.php?url='.$ip;
  58. try{
  59. $ret = json_decode(Curl::send($url), TRUE);
  60. if(!$ret){
  61. Log::warning("【PING】检测".$ip."时,接口返回异常访问链接:".$url);
  62. return FALSE;
  63. }elseif($ret['code'] != 1 || $ret['msg'] != "检测成功!"){
  64. Log::warning("【PING】检测".$ip."时,返回".json_encode($ret));
  65. return FALSE;
  66. }
  67. }catch(Exception $e){
  68. Log::warning("【Ping】检测".$ip."时,接口请求超时".$e);
  69. return FALSE;
  70. }
  71. return $ret['data']; // 服务器宕机
  72. }
  73. }
  74. ?>