Teja
Teja

Reputation: 41

Cannot send data over UDP in UWP

I am trying to send the data over UDP in UWP Application. However, I cannot see the data being sent on Wireshark.

Just to check if firewall is causing any issue, I disabled it and tried sending the data again. However, I still don't see the data on Wireshark. Here's my code:

UdpClient client = new UdpClient();
client.EnableBroadcast = true;
client.Connect(IPAddress.Broadcast, 9520);
Byte[] senddata = Encoding.ASCII.GetBytes("Hello!");
client.Send(senddata, senddata.Length);
client.Close();

Am I missing something obvious here? I am using Visual Studio 2017 to build this UWP Application.

Upvotes: 1

Views: 410

Answers (2)

Teja
Teja

Reputation: 41

This page explains why the above code will not work if the App capabilities were not configured.

I didn't configure the capabilities before asking this question. However, I came across the page and enabled some capabilities (Internet(Client & Server), Internet(Client), Private Networks(Client & Server)).

After configuring them, my earlier code is working fine.

If you're facing the same problem, please configure the capabilities by going to Package.appxmanifest -> Capabilities and then rebuild the solution. After correctly enabling the capabilities, your app shall send the data. :) :)

Upvotes: 3

Mert Akkanat
Mert Akkanat

Reputation: 141

You can use codes below I write and test it, it works fine

        byte[] package= Encoding.ASCII.GetBytes(udpInfo[2].ToString());
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(udpInfo[0].ToString()), Convert.ToInt32(udpInfo[1]));
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        try
        {
            sock.SendTo(package, ep); //send packet to sw ip
            Console.WriteLine("package sent");
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("package can't sent");
            return false;
        }

EDIT: udpInfo arraylist declaration below:

public ArrayList udpInfo = new ArrayList(); // 0-ip 1-port 2-command
udpInfo[0] = "192.168.1.1"
udpInfo[1] = 1111
udpInfo[2] = "some commands"

Upvotes: 0

Related Questions