php socket connection using localhost through Telnet

2k Views Asked by At

I been trying to create socket and bind it to the localhost 127.0.0.1 and trying to connect to it using Microsoft's telnet service, but where ever I connect to the specified address and port I get the following error.

PHP Warning: socket_write(): unable to write to socket [0]: A request to sen d or receive data was disallowed because the socket is not connected and (when s ending on a datagram socket using a sendto call) no address was supplied.

A similar error is returned by the socket_read, I dont understand telnet should just work right giving a socket_connect request to the localhost.

Here's the code:

set_time_limit(0);
$socket=null;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(socket_bind($socket,"127.0.0.1",58)){    
    if(!socket_listen($socket,0)){
        echo "Problem Listening to the socket";
    }do{
        $res=socket_accept($socket);
        $write="\n Hello the connection has been established";  
        if(!socket_write($socket,$write,strlen($write))){
            echo "Problem Reading the and writing to the socket";
            }                   
            do{
            if(!$clientmsg=socket_read($socket,2048,PHP_NORMAL_READ)){
                echo "Error reading Client Msg";
                break;
                    }
            $repsonse= "Thanks for you input";
            socket_write($socket,$response,strlen($response));
            if($nclientmsg=trim($clientmsg)){
                continue;
            }
            if($clientmsg="close"){
                socket_close($socket);
                echo "The socket has been closed as promised Thanks";
                break 3;
                }
            }while(true);
            }while(true);
}else{
    echo "Problem connecting to the socket.Unable to bind to the specified address";
}

Thanks.

1

There are 1 best solutions below

3
On

your code does not socket_connect anywhere.. you need to socket_connect BEFORE you can socket_write (for tcp & telnet.. udp is a different story)... anyway, here's an example code for connecting to a telnet server:

<?php
    $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket===false){
    throw new Exception("socket_create() failed: reason: " . socket_strerror(socket_last_error()));
}
assert(socket_set_block ( $socket)===true);
assert(socket_bind($socket,0,mt_rand(1024,5000))!==false);//TODO: don't use mt_rand... it has a (small) chance choosing a used address..
if(socket_connect($socket,
'131.252.208.48',7680
)!==true){
       throw new Exception("socket_connect() failed: reason: " . socket_strerror(socket_last_error($socket)));
}
echo "connected!";
$buffer="";
do{
    sleep(1);
    socket_recv($socket,$buffer,100,0);
    echo $buffer;
} while(strlen($buffer)>1);
socket_close($socket);

-- i do something similar in this code https://github.com/divinity76/outcastshit/blob/master/LoginWithPHP.php