通过Telnet

时间:2015-08-22 14:08:52

标签: php sockets php-socket

我一直在尝试创建套接字并将其绑定到localhost 127.0.0.1并尝试使用Microsoft的telnet服务连接到它,但是无论我连接到指定的地址和端口,我都会收到以下错误。

  

PHP警告:socket_write():无法写入socket [0]:对sen的请求   d或接收数据是不允许的,因为套接字没有连接(当s   使用sendto调用以数据报套接字结束)没有提供地址。

socket_read返回了类似的错误,我不明白telnet应该正确地向localhost发出socket_connect请求。

以下是代码:

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";
}

感谢。

1 个答案:

答案 0 :(得分:0)

你的代码没有socket_connect在任何地方..你需要socket_connect之前你可以socket_write(对于tcp& telnet ... udp是一个不同的故事)...无论如何,这里是一个连接到a的示例代码telnet服务器:

<?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);

- 我在此代码https://github.com/divinity76/outcastshit/blob/master/LoginWithPHP.php

中做了类似的事情