我試圖發送一個udp廣播,並在c#中收到答案。雖然發送廣播的作品完美,我沒有收到任何答案在C#中。但是,當我把使用Wireshark一看,我可以看到一個答案已發出:接收UDP廣播(C#)的答案
- 從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#代碼:調用udpClient.Receive時
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);
}
}
程序停止。任何人都可以幫助我嗎? :)