Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper and fast way to TELNET in PHP. Sockets or cURL

Almost all examples of the TELNET implementations in PHP are with sockets (fsockopen). This does not work for me, because it takes an unacceptable amount of time (~ 60 seconds).

I have tried fsockopen for other purposes and found it slow in contrast to cURL.

Question #1: Why are sockets that slow?

Update: I found we need to set stream_set_timeout function, and we can control the socket execution time. I'm curious how to set the proper timeout or how to make it "stop waiting" once the response is received.


I can't get the same thing implemented with cURL. Where should I put the commands which I need to send to telnet? Is CURLOPT_CUSTOMREQUEST the proper option? I'm doing something like this:

class TELNETcURL{

    public $errno;
    public $errstr;
    private $curl_handle;
    private $curl_options = array(
        CURLOPT_URL => "telnet://XXX.XXX.XXX.XXX:<port>",
        CURLOPT_TIMEOUT => 40,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HEADER => FALSE,
        CURLOPT_PROTOCOLS => CURLPROTO_TELNET
    );

    function __construct(){
        $this->curl_handle = curl_init();
        curl_setopt_array($this->curl_handle, $this->curl_options);
    }

    public function exec_cmd($query) {
        curl_setopt($this->curl_handle, CURLOPT_CUSTOMREQUEST, $query."\r\n");
        $output = curl_exec($this->curl_handle);
        return $output;
    }

    function __destruct(){
        curl_close($this->curl_handle);
    }

}

And then something similar to this:

$telnet = new TELNETcURL();
print_r($telnet->exec_cmd("<TELNET commands go here>"));    

I am getting "Max execution time exceeded 30 seconds" on curl_exec command.

Question #2: What is wrong with the cURL implementation?

like image 495
wyxa Avatar asked Dec 07 '11 06:12

wyxa


1 Answers

what you need to be doing is using NON-Blocking IO and then Poll for the response. what you are doing now is waiting/hanging for a response that never comes -- thus the timeout.

Personally I've written a lot of socket apps in php they work great -- and I detest cURL as buggy, cumbersome, and highly insecure... just read their bug list you should be appalled.

Go read the Excellent PHP manual complete with many examples for how to do Polled IO they even give you an example telnet server & client.

like image 63
codeslinger Avatar answered Sep 21 '22 00:09

codeslinger