从 PHP 发送 UDP 广播并在 C# 中接收
我正在尝试向 C# 应用程序发送广播 UDP 消息。我已尝试使用以下代码来发送消息。我在 php.net 网站上找到了评论 socket_sendto 手册页。
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>
这对我不起作用,也许是我的网络问题。
但如果我将广播 IP '255.255.255.255'
替换为我的特定 IP,例如 '192.168.1.128'
,它确实有效。我可以通过 Wireshark 看到此消息,但使用上面的代码看不到此消息。这让我相信 PHP 方面的代码有问题。我真的想在我的程序中使用广播或某种多播,所以我现在有点卡住了;)
我在(C#)接收端使用以下内容(用于测试):
UdpClient subscriber = new UdpClient(15000);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 15000); ;
byte[] pdata = subscriber.Receive(ref ep);
string data = Encoding.ASCII.GetString(pdata);
MessageBox.Show(data);
subscriber.Close();
知道可能是什么原因吗这个?
I'm trying to send a broadcast UDP message to a C# application. I have tried the following code to send the message. Which I found on the php.net website as a comment to the socket_sendto manual page.
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>
This doesn't work for me, maybe it's my network.
But it does work if I replace the broadcast IP '255.255.255.255'
to my specific IP e.g. '192.168.1.128'
. I can see this message coming in with Wireshark, while I can't see this using the above code. This leads me to believe there is something wrong with the PHP side of the code. I really want to use broadcasting or some kind of multicasting for my program, so I'm a bit stuck at the moment ;)
I use the following on the (C#) receiving end (for testing):
UdpClient subscriber = new UdpClient(15000);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 15000); ;
byte[] pdata = subscriber.Receive(ref ep);
string data = Encoding.ASCII.GetString(pdata);
MessageBox.Show(data);
subscriber.Close();
Any idea what could be the cause of this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在脚本中指定
MSG_DONTROUTE
标志。从这篇 CodeGuru 帖子 中获取灵感,如果这不是'指定路由器决定是否广播您的消息。Try specifying the
MSG_DONTROUTE
flag in your script. Taking inspiration from this CodeGuru post, if this isn't specified the routers make the decision on whether or not to broadcast your message.255.255.255.255 是“有限”广播,而 192.168.1.255 是“定向”广播。
限制简单来说就是只在局域网内发送。 LAN 由直接连接的主机定义,即中间没有路由器。路由器(除了少数例外)不传递有限广播,而是传递定向广播。
现在,根据您最初的问题和问题,我只能猜测您正在通过路由器发送广播。
255.255.255.255 is a "limited" broadcast whereas your 192.168.1.255 is a "directed" broadcast.
Limited in simple terms means that it is only send within the LAN. LAN as defined by directly connected hosts, i.e. with no router in between. Routers--with a few exceptions--do not pass a limited broadcast but a directed broadcast.
Now, with your initial problem and question, I can only guess that you are sending your broadcast across a router.