【问题标题】:Search server with UDP使用 UDP 的搜索服务器
【发布时间】:2019-09-23 17:51:23
【问题描述】:

代码的任务是找到回答#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();
        }
'''

【问题讨论】:

  • 以255结尾的IP地址不是服务器IP地址。它是网关机器中的服务器处理的子网的广播地址。您无法连接到该地址。你想实现什么协议?
  • 你能写一些发送UDP套接字并等待回复的示例代码吗?

标签: c# search server udp


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2019-07-13
    相关资源
    最近更新 更多