接收UDP广播(C#)的答案
发布时间:2020-12-15 21:18:57 所属栏目:百科 来源:网络整理
导读:我正在尝试发送udp广播,并在c#中收到答案.虽然发送广播完美,但我没有收到任何c#的答案.但是当我看看wireshark时,我可以看到已经发送了一个答案: 从192.168.0.141发送到192.168.0.255 从192.168.0.105发送到255.255.255.255(这将是答案) Wireshark日志: 1 0
我正在尝试发送udp广播,并在c#中收到答案.虽然发送广播完美,但我没有收到任何c#的答案.但是当我看看wireshark时,我可以看到已经发送了一个答案:
>从192.168.0.141发送到192.168.0.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,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时程序停止.任何人都可以帮助我PLZ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |