Getting UDP packet datagrams in PHP

I am working in php to create a listening server for a GPS tracking system. GPS sends data via UDP packets, which I can display by running the script below. However, the actual data is displayed in characters, so I assume that I do not have enough conversion

    //Reduce errors
    error_reporting(~E_WARNING);

    //Create a UDP socket
    if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        die("Couldn't create socket: [$errorcode] $errormsg \n");
    }

    echo "Socket created \n";

    // Bind the source address
    if( !socket_bind($sock, "192.168.1.29" , 1731) )
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        die("Could not bind socket : [$errorcode] $errormsg \n");
    }

    echo "Socket bind OK \n";

    //Do some communication, this loop can handle multiple clients
    while(1)
    {
        echo "\n Waiting for data ... \n";

        //Receive some data
        $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
        echo "$remote_ip : $remote_port -- " . $buf;

            //Send back the data to the client
        //socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);

    }

    socket_close($sock);
+4
source share
1 answer

I have not done this before with PHP, but first I assume that you will get the binary string back, which you will need to convert to ASCII (or any other character set that you use).

It looks like you should use PHP unpack for this.

, , , . , , , ( , ), ASCII, chr. :

//Receive some data
$r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
//Convert to array of decimal values
$array = unpack("c*chars", $buf);
//Convert decimal values to ASCII characters:
$chr_array = array();
for ($i = 0; $i < count($array); $i++)
{
    $chr_array[] = chr($array[$i]);
}

, (.. ..). ).

EDIT: , , 'chars' .

EDIT: ASCII .

+2

All Articles