我正在尝试发送一个 udp 广播,并在 c# 中接收一个答案。虽然发送广播效果很好,但我在 c# 中没有收到任何答复。但是当我用 wireshark 查看时,我可以看到已经发送了一个答案:
- 从 192.168.0.141 发送到 192.168.0.255
- 从 192.168.0.105 发送到 255.255.255.255(这就是答案)
Wireshark 日志:
1 0.000000 192.168.0.141 192.168.0.255 UDP Source port: 55487 Destination port: 17784
2 0.000851 192.168.0.105 255.255.255.255 UDP Source port: 17784 Destination port: 55487
那是我的 C# 代码:
private static byte[] SendBuffer = new byte[] { 1, 2, 3 };
public static void SendAndReceiveBroadcast( byte[] data, IPEndPoint broadcastEndpoint )
{
using( Socket broadcastSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ) )
{
broadcastSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1 );
broadcastSocket.SendTo( data, broadcastEndpoint );
receivePort = broadcastSocket.LocalEndPoint.ToString().Split( ':' )[1];
Console.WriteLine( "Sent {0} from Port {1}", CollectionsHelper.ItemsToString( data, "{0:X2}" ), broadcastSocket.LocalEndPoint.ToString() );
broadcastSocket.Close();
}
using( Socket receiveSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ) )
{
IPEndPoint broadcastAddress = new IPEndPoint( IPAddress.Any, Convert.ToInt32( receivePort ) );
UdpClient udpClient = new UdpClient();
udpClient.Client.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true );
udpClient.Client.Bind( broadcastAddress );
IPEndPoint remoteIP = new IPEndPoint( IPAddress.Any, Convert.ToInt32( receivePort ) );
byte[] answer = udpClient.Receive( ref remoteIP );
}
}
程序在调用 udpClient.Receive 时停止。谁能帮我吗? :)
最佳答案
由于您使用相同的进程来发送和接收,因此您需要在发送消息之前打开接收器,并且您需要使用 udpClient.ReceiveAsync() 并在允许您的程序关闭之前等待应答.
关于c# - 接收对 UDP 广播的应答 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6152489/