使用未知端口发送广播

时间:2015-02-05 21:49:11

标签: c# .net networking udp broadcast

是否可以发送广播以搜索服务器应用程序,如果我不知道服务器正在运行的端口?或者我必须检查每个端口?

要发送一个简单的广播,我在互联网上找到了以下代码:

服务器

Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.Write("Running server..." + Environment.NewLine);
server.Bind(new IPEndPoint(IPAddress.Any, 48000));

while (true)
{
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint tempRemoteEP = (EndPoint)sender;
    byte[] buffer = new byte[1000];

    server.ReceiveFrom(buffer, ref tempRemoteEP);

    Console.Write("Server got '" + buffer[0] + "' from " + tempRemoteEP.ToString() + Environment.NewLine);

    Console.Write("Sending '2' to " + tempRemoteEP.ToString() +
    Environment.NewLine);

    server.SendTo(new byte[] { 2 },
    tempRemoteEP);
}

客户端

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 48000);

//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);

//Send message to everyone
client.SendTo(new byte[] { 1 }, AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];

string serverIp;

try
{
    //Recieve from server. Don't wait more than 3000 milliseconds.
    client.SetSocketOption(SocketOptionLevel.Socket,
    SocketOptionName.ReceiveTimeout, 3000);
    client.ReceiveFrom(buffer, ref tempRemoteEP);
    Console.Write("Client got '" + buffer[0] + "' from " +
    tempRemoteEP.ToString() + Environment.NewLine);

    //Get server IP (ugly)
    serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
}
catch
{
    //Timout. No server answered.
    serverIp = "?";
}

Console.Write("ServerIp: " + serverIp + Environment.NewLine);
Console.ReadLine();

但我不知道,我的服务器使用端口48000

1 个答案:

答案 0 :(得分:0)

发送广播:

var port = 123;
var udp = new UdpClient();
var data = new byte[] { 1, 2, 3 };
udp.Send(data, data.Length, new IPEndPoint(IPAddress.Any, port));

如果您不知道该端口,则必须尝试所有端口,我不建议这样做,因为您是在向网络发送垃圾邮件。

你想做什么?