使用 UDP 搜索服务器

Search server with UDP

代码的任务是找到回答#SERVER 问题的服务器。如果我输入服务器的 IP 地址工作正常,但不是在 192.168.1.255 地址。

感谢您的帮助!

我的代码在这里:

static void Main(string[] args)
        {
            Console.WriteLine(IPAddress.IPv6Any);

            UdpClient udpClient = new UdpClient();

            try
            {

                udpClient.EnableBroadcast = true;
                udpClient.Connect("192.168.1.255",80);


                // Sends a message to the host to which you have connected.
                Byte[] sendBytes = Encoding.ASCII.GetBytes("#SERVER");

                udpClient.Send(sendBytes, sendBytes.Length);

                //IPEndPoint object will allow us to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                string returnData = Encoding.ASCII.GetString(receiveBytes);

                // Uses the IPEndPoint object to determine which of these two hosts responded.
                Console.WriteLine("This is the message you received " +
                                             returnData.ToString());
                Console.WriteLine("This message was sent from " +
                                            RemoteIpEndPoint.Address.ToString() +
                                            " on their port number " +
                                            RemoteIpEndPoint.Port.ToString());

                udpClient.Close();


            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.ReadKey();
        }
'''

192.168.1.255或更好任何以 255 结尾的 IP 地址都是广播地址。 发送到此 IP 的消息没有特定目标,但(在大多数情况下)将广播到您网络中的所有设备(例外情况可能取决于您的本地配置)。您网络中的设备是否对广播消息做出反应取决于它们的配置。但是,像您一样向广播地址发送发现消息没有多大意义,因为不允许将此 IP 地址分配给任何设备。