【发布时间】: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套接字并等待回复的示例代码吗?