dongliqin6939 2013-05-08 11:38
浏览 32
已采纳

fsockopen()总是返回true

Hi I am trying to incorporate a function in my project that will ping my app servers and see if they are running or not. Problem is, everytime I try to use this function it always returns that they are alive, even though I am in my local environment, and there are no servers at those IP addresses. So whats going on?

Here is my function:

function ping($host, $port, $timeout) { 
    if($fp = fsockopen($host,$port,$errCode,$errStr,$timeout)){   
       return 'Alive';
    } else {
       return 'Not alive'; 
    } 
    fclose($fp);
}

Here is how I am calling the function:

    foreach ($appservers as $key => $value) {
        echo ping($value['privateip'] , 80, 1).'<br/>';
    }

Here is my array of server variables:

$appservers = array(
'app1' => array(
    'publicdns' => 'app1.xxxx.com',
    'privateip' => '1.1.1.101',
    'alive' => NULL,
    'active_users' => NULL
),

'app2' => array(
    'publicdns' => 'app2.xxxx.com',
    'privateip' => '1.1.1.102',
    'alive' => NULL,
    'active_users' => NULL
),

'app3' => array(
    'publicdns' => 'app3.xxxx.com',
    'privateip' => '1.1.1.103',
    'alive' => NULL,
    'active_users' => NULL
),

'app4' => array(
    'publicdns' => 'app4.xxxx.com',
    'privateip' => '1.1.1.104',
    'alive' => NULL,
    'active_users' => NULL
)

);

  • 写回答

1条回答 默认 最新

  • douwen0647 2013-05-08 11:49
    关注

    Have see this issue before , You are using a DNS service that resolves non-existent domains to a server that gives you a "friendly" error page, which it returns with a 200 response code.

    See : get_headers Inconsistency for more details of this issue.

    You can resolve it with DavidRandom solution

    var_dump(ping("stackoverflow.com", 30, 1)); // port 30 return false
    var_dump(ping("stackoverflow.com", 80, 1)); // port 80; returns 0.49000000953674
    

    Your Function Modified

    function ping($host, $port, $timeout) {
        $a = gethostbyname('idontexist.tld');
        $b = gethostbyname($host);
    
        if ($a == $b)
            return false;
    
        $time = microtime(true);
        $fp = @fsockopen($host, $port, $errCode, $errStr, $timeout);
        $time = microtime(true) - $time;
        if ($fp) {
            fclose($fp);
            return $time;
        } else {
            return false;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面