Menu

UDP

Majenko Technologies

The UDP object is perhaps the most simple of the communication socket objects.

You first create the UDP object itself, specifying the local port number:

UDP mySocket(10000);

All packets sent will be from that port number, and packets arriving into that port number will be added to the UDP port queue.

You then need to add the socket to the networking stack:

Network.addPort(mySocket);

Sending and receiving packets is as simple as:

mySocket.send(ipAddress, remotePort, data, length);

The ipAddress is an unsigned long type and can be created using the quad2ip function. For example, to send 200 bytes of data to port 20000 on 192.168.0.80 you would use:

mySocket.send(quad2ip(192,168,0,80), 20000, myData, 200);

Where myData is a pointer to the data in unsigned char format.

Receiving is done with the .recv() method:

len = mySocket.recv(data);

The data from the packet is stored in the unsigned char buffer pointer to by data and the number of bytes received is returned.

To find out where data is coming from, you can inspect the sender IP and sender port of the next packet in the queue using:

ip = mySocket.peerAddress();

and

port = mySocket.peerPort();

Be sure to do that before reading the packet with recv() or you will be looking at the next packet in the queue.

To find out if there are any packets available for reading you can use the available() method:

avail = mySocket.available();

That returns the number of packets in the incoming queue, much like the Serial.available() method. You should check that value before doing any reading of the packets.


Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.