Php – way to specify the source UDP port using PHP

phpudp

I need to send a message via UDP to a remote equipment. I know that if I use the same UDP port that it used while sending information to the server to write back to it the messages goes through.

I am currently using:

        $fp = fsockopen( $destination, $port, $errno, $errstr);
        if (!$fp) {
           echo "ERROR: $errno - $errstr\n";
        } else {
           fwrite($fp, $m);
           fclose($fp);
        }

But in this way I have no control of which port is going to be used as the source port.

In Java have one can use:

       client = new DatagramSocket(21000);

Is there a way to do something similar using PHP.

Best Solution

You could do it by creating a normal udp socket with socket_create() and using socket_bind() to bind it to a specific port. Then use e.g. socket_sendto for specifying the endpoint and port to send it to. Example code follows.

A simple server that spits out the port number and ip address of client using socket_stream_server():

 <?php

 set_time_limit (20);

 $socket = stream_socket_server("udp://127.0.0.1:50000",
                                $errno, $errstr, 
                                STREAM_SERVER_BIND);
 if (!$socket) {
     die("$errstr ($errno)");
 }

 do {
     $packet = stream_socket_recvfrom($socket, 1, 0, $peer);
     echo "$peer\n";
     stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
 } while ($packet !== false);

 ?>

and the client is like this:

<?php

$address = '127.0.0.1';
$port = 50001;
$dest_address = '127.0.0.1';
$dest_port = 50000;

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

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed:" . socket_strerror(socket_last_error($sock)) . "\n";
}

$msg = "Ping !";  
socket_sendto($sock, $msg, strlen($msg), 0, $dest_address, $dest_port);
socket_close($sock);

?>

Running the server (on the command line) gives this output when running the client multiple times:

<knuthaug@spider php>php server.php
127.0.0.1:50001
127.0.0.1:50001
127.0.0.1:50001
^C
<knuthaug@spider php>
Related Question