有没有一种方法可以指定使用PHP的源UDP端口?
问题描述:
我需要通过UDP发送消息到远程设备。我知道,如果我使用与将信息发送到服务器以回写消息时使用的UDP端口相同的UDP端口,则消息会通过。有没有一种方法可以指定使用PHP的源UDP端口?
我目前正在使用:
$fp = fsockopen($destination, $port, $errno, $errstr); if (!$fp) { echo "ERROR: $errno - $errstr\n"; } else { fwrite($fp, $m); fclose($fp); }
但这种方式我无法控制它的端口将被用作源端口。
在Java中有一个可以使用:
client = new DatagramSocket(21000);
有没有办法使用PHP做类似的事情。
答
你可以通过创建一个带有socket_create()
的普通udp套接字并使用socket_bind()
将其绑定到特定的端口来完成。然后使用例如socket_sendto用于指定要发送到的端点和端口。示例代码如下。
该吐出使用socket_stream_server()
客户端的端口号和IP地址的简单的服务器:
<?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);
?>
和客户端是这样的:
<?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);
?>
运行服务器(在命令行上)在多次运行客户端时给出此输出:
<[email protected] php>php server.php
127.0.0.1:50001
127.0.0.1:50001
127.0.0.1:50001
^C
<[email protected] php>
如果您打算使用此公司请记住,您可能需要确保您支持套接字。
– Sebas 2009-07-03 04:44:01