NetworkDetection.php 2.2 KB

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