开发者

how solve PHP Parse error when use socket_bind

i want fetch UDP packet, so i write this code:

<?PHP
error_reporting(-1);

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

socket_bind($socket, '127.0.0.1', 2055);

$from = '192.168.1.2';
$port = 20开发者_开发技巧55;

socket_recvfrom($socket, $buf, 12, 0, $from, $port);

while(1==1){
echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
}
?>

when i run it with PHP command , i got this error:

PHP Parse error:  syntax error, unexpected single-quoted string "127.0.0.1", expecting ")" in C:\Users\ELAY\php on line 7

i try it with PHP 8 , 7.5 , 5.6


Try this way

   <?php
    
    // Create a socket resource
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    
    // Bind the socket to an IP address and port
    $result = socket_bind($socket, '0.0.0.0', 1234);
    
    if ($result === false) {
        // Handle the error
        $errorCode = socket_last_error($socket);
        $errorMessage = socket_strerror($errorCode);
        echo "Failed to bind the socket: $errorMessage ($errorCode)\n";
    } else {
        // Read data from the socket
        $data = socket_read($socket, 1024);
        if ($data === false) {
            // Handle the error
            $errorCode = socket_last_error($socket);
            $errorMessage = socket_strerror($errorCode);
            echo "Failed to read from the socket: $errorMessage ($errorCode)\n";
        } else {
            // Do something with the data
            echo "Received data: $data\n";
        }
    }

In this code, there is a syntax error on the line where the socket_bind function is called. The second argument to this function should be a string containing an IP address or hostname, but in this code it is a numeric zero. This will cause a parse error because PHP expects a string, but it receives a numeric value instead.

To fix this error, you will need to change the second argument to the socket_bind function to a valid IP address or hostname. For example, you could use '127.0.0.1' to bind the socket to the localhost address, or you could use a specific IP address or hostname for your network.

Once you have fixed this syntax error, your code should be able to run without encountering a parse error. You can then continue to read data from the socket and process it as needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜