Status checker for hundreds IP addresses

前端 未结 10 1576
长发绾君心
长发绾君心 2021-01-02 01:52

I wonder how to make a status checker, checking about 500 addresses in a few minutes? (it\'ll check a certain port if its listening).

But I care about the performanc

10条回答
  •  温柔的废话
    2021-01-02 02:19

    This is very doable in PHP and you could check 500 IP in a few seconds. Use mutli-curl to send out many requests at once (i.e. 100 or all 500). It will take only as long as the slowest IP to respond. But you may want to set a reasonable curl connect timeout of a few seconds. Default network timeout is 2 minutes as I recall. http://php.net/manual/en/function.curl-multi-exec.php

    Note that I'm not saying PHP is your best choice for something like this. But it can be done fairly quickly and easily in PHP.

    Here is a full code example. I tested it with real URLs and it all worked. The $results array will contain just about all the stats you can get from a curl request. In your case, since you just care if the port is "open" you do a HEAD request by setting CURLOPT_NOBODY to true.

    $urls    = array(
        'http://url1.com'=>'8080',
        'http://url2'=>'80',
        );
    $mh        = curl_multi_init();
    $url_count    = count($urls);
    $i        = 0;
    foreach ($urls as $url=>$port) {
        $ch[$i] = curl_init();
        curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch[$i], CURLOPT_NOBODY, true);
        curl_setopt($ch[$i], CURLOPT_URL, $url);
        curl_setopt($ch[$i], CURLOPT_PORT, $port);
        curl_multi_add_handle($mh, $ch[$i]);
        $i++;
    }
    $running    = null;
    do {
        $status    = curl_multi_exec($mh,$running);
        $info     = curl_multi_info_read($mh);
    } while ($status == CURLM_CALL_MULTI_PERFORM || $running);
    
    $results= array();
    for($i = 0; $i < $url_count; $i++) {
        $results[$i]     = curl_getinfo($ch[$i]);
        // append port number request to URL
        $results[$i]['url']    .= ':'.$urls[$results[$i]['url']];
        if ($results[$i]['http_code']==200) {
            echo $results[$i]['url']. " is ok\n";
        } else {
            echo $results[$i]['url']. " is not ok\n";
        }
        curl_multi_remove_handle($mh, $ch[$i]);
    }
    
    curl_multi_close($mh);
    print_r($results);
    

提交回复
热议问题