SOCK_STREAM is working fine, but PHP SOCK_RAW is not. Anyone have any example?

Viewed 15

So I have tested socket with this piece of code, it is working fine (SOCK_STREAM)

   <?php    
        set_time_limit(0);
        
        $sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket \n");
        $result = socket_bind($sock, $host, $port) or die("Could not bind to socket \n");
        
        $result = socket_listen($sock, 3) or die("Dould not set up socket listener \n");
        echo "Listening for connection \n";
        
        // LOOP FOREVER
        do {
                $accept = socket_accept($sock) or die ("Could not accept incoming connection \n");
                $msg = socket_read($accept, 100000) or die("Could not read input \n");
        
                echo "Client says: " . $msg . "\n\n\n";
        
        } while(true);
        
        socket_close($accept, $sock);

But the problem is when i try to change the socket_create() to SOCK_RAW

$sock = socket_create(AF_INET, SOCK_RAW, 1) or die("Could not create socket \n");

or

$sock = socket_create(AF_INET, SOCK_RAW, 0) or die("Could not create socket \n");

or

$sock = socket_create(AF_INET, SOCK_RAW, getprotobyname('icmp')) or die("Could not create socket \n");

I have the following error:

PHP Warning:  socket_listen(): unable to listen on socket [10045]: The attempted operation is not supported for the type of object referenced in C:\xampp\htdocs\wialon php script\server.php on line 10

Warning: socket_listen(): unable to listen on socket [10045]: The attempted operation is not supported for the type of object referenced in C:\xampp\htdocs\wialon php script\server.php on line 10
Dould not set up socket listener

Please help. Thank you in advance.

1 Answers

You can't use socket_listen() (and by extension, socket_accept()) with RAW sockets. They are only meaningful for connection-oriented (ie: TCP, etc) sockets. The PHP documentation even says so:

https://www.php.net/manual/en/function.socket-listen.php

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

https://www.php.net/manual/en/function.socket-accept.php

After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket.

Related