quantum32043
quantum32043

Reputation: 1

UDP Broadcast in C# only works on the machine that runs it

There is the following host test code:

    string localIP = IP.ToString();
    UdpClient udpClient = new UdpClient();
    udpClient.EnableBroadcast = true;
    IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 11000);
    try
    {
        var counter = 0;
        while (counter < 5)
        {
            byte[] sendBytes = Encoding.ASCII.GetBytes(localIP);
            udpClient.Send(sendBytes, sendBytes.Length, broadcastEndPoint);
            counter++;
            Thread.Sleep(5000);
        }        
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
    finally
    {
    udpClient.Close();
    }

And the folowing code for the client:

    UdpClient udpClient = new UdpClient(11000);
    string receivedData = null;
    try
    {
        IPEndPoint receiveEndPoint = new IPEndPoint(IPAddress.Any, 11000);
        byte[] receiveBytes = udpClient.Receive(ref receiveEndPoint);
        receivedData = Encoding.ASCII.GetString(receiveBytes);
        Console.WriteLine("Received broadcast from receiveEndPoint.ToString() : receivedData)\n");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
    finally
    {
        udpClient.Close();
    }

When the host and client are launched on the same machine, everything works correctly and packets reach the client. However, after I tried to run them on different machines connected to the same local network (the modem mode on the phone acted as the local network), the packets stopped arriving. The firewall is disabled on both machines, so I have no idea what the problem might be

I tried sending the broadcast to a smaller range (192.255.255.255), but this also did not help. When you try to debug the client, the debugger stops and the program stops showing any signs of life on the receivedData = Encoding.ASCII.GetString(receiveBytes) line. I hope someone can suggest a solution

Upvotes: 0

Views: 42

Answers (1)

quantum32043
quantum32043

Reputation: 1

I found a solution to the problem. Broadcast IP had to be calculated for each local network used separately. I just get the local network address, its mask, use it to calculate the broadcast IP for this network and send udp packets to it

Upvotes: 0

Related Questions