Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

UDP Protocol

In computer networking, the UDP stands for User Datagram Protocol. The David P. Reed
developed the UDP protocol in 1980. It is defined in RFC 768, and it is a part of
the TCP/IP

protocol, so it is a standard protocol over the internet. The UDP protocol allows the computer
applications to send the messages in the form of datagrams from one machine to another
machine over the Internet Protocol (IP)
network. The UDP is an alternative communication protocol to the TCP protocol (transmission
control protocol). Like TCP, UDP provides a set of rules that governs how the data should be
exchanged over the internet. The UDP works by encapsulating the data into the packet and
providing its own header information to the packet. Then, this UDP packet is encapsulated to the
IP packet and sent off to its destination. Both the TCP and UDP
protocols send the data over the internet protocol network, so it is also known as TCP/IP
and UDP/IP. There are many differences between these two protocols. UDP enables the process
to process communication, whereas the TCP provides host to host communication. Since UDP
sends the messages in the form of datagrams, it is considered the best-effort mode of
communication. TCP
sends the individual packets, so it is a reliable transport medium. Another difference is that the
TCP is a connection-oriented protocol whereas, the UDP is a connectionless protocol as it does
not require any virtual circuit to transfer the data.

UDP also provides a different port number to distinguish different user requests and
also provides the checksum capability to verify whether the complete data has arrived or
not; the IP

layer does not provide these two services.

Features of UDP protocol


The following are the features of the UDP protocol:

o Transport layer protocol

UDP

is the simplest transport layer communication protocol


. It contains a minimum amount of communication mechanisms. It is considered an unreliable
protocol, and it is based on best-effort delivery services. UDP provides no acknowledgment
mechanism, which means that the receiver does not send the acknowledgment for the received
packet, and the sender also does not wait for the acknowledgment for the packet that it has sent.
o Connectionless
The UDP is a connectionless protocol as it does not create a virtual path to transfer the
data. It does not use the virtual path, so packets are sent in different paths between the
sender and the receiver, which leads to the loss of packets or received out of order.

Ordered delivery of data is not guaranteed.

In the case of UDP, the datagrams are sent in some order will be received in the same
order is not guaranteed as the datagrams are not numbered.

o Ports

The UDP protocol uses different port numbers so that the data can be sent to the
correct destination. The port numbers are defined between 0 and 1023.

o Faster transmission

UDP enables faster transmission as it is a connectionless protocol, i.e., no virtual path is


required to transfer the data. But there is a chance that the individual packet is lost,
which affects the transmission quality. On the other hand, if the packet is lost in TCP
connection, that packet will be resent, so it guarantees the delivery of the data packets.

o Acknowledgment mechanism

The UDP does have any acknowledgment mechanism, i.e., there is no handshaking
between the UDP sender and UDP receiver. If the message is sent in TCP, then the
receiver acknowledges that I am ready, then the sender sends the data. In the case of
TCP, the handshaking occurs between the sender and the receiver, whereas in UDP,
there is no handshaking between the sender and the receiver.

o Segments are handled independently.

Each UDP segment is handled individually of others as each segment takes different
path to reach the destination. The UDP segments can be lost or delivered out of order
to reach the destination as there is no connection setup between the sender and the
receiver.

o Stateless

It is a stateless protocol that means that the sender does not get the acknowledgement
for the packet which has been sent.
Why do we require the UDP protocol?
As we know that the UDP is an unreliable protocol, but we still require a UDP protocol in
some cases. The UDP is deployed where the packets require a large amount of
bandwidth along with the actual data. For example, in video streaming, acknowledging
thousands of packets is troublesome and wastes a lot of bandwidth. In the case of video
streaming, the loss of some packets couldn't create a problem, and it can also be
ignored.

UDP Header Format

In UDP, the header size is 8 bytes, and the packet size is upto 65,535 bytes. But this
packet size is not possible as the data needs to be encapsulated in the IP datagram, and
an IP packet, the header size can be 20 bytes; therefore, the maximum of UDP would be
65,535 minus 20. The size of the data that the UDP packet can carry would be 65,535
minus 28 as 8 bytes for the header of the UDP packet and 20 bytes for IP header.

The UDP header contains four fields:

o Source port number: It is 16-bit information that identifies which port is going t
send the packet.
o Destination port number: It identifies which port is going to accept the
information. It is 16-bit information which is used to identify application-level
service on the destination machine.
o Length: It is 16-bit field that specifies the entire length of the UDP packet that
includes the header also. The minimum value would be 8-byte as the size of the
header is 8 bytes.
o Checksum: It is a 16-bits field, and it is an optional field. This checksum field
checks whether the information is accurate or not as there is the possibility that
the information can be corrupted while transmission. It is an optional field, which
means that it depends upon the application, whether it wants to write the
checksum or not. If it does not want to write the checksum, then all the 16 bits
are zero; otherwise, it writes the checksum. In UDP, the checksum field is applied
to the entire packet, i.e., header as well as data part whereas, in IP, the checksum
field is applied to only the header field.

Concept of Queuing in UDP protocol

In UDP protocol, numbers are used to distinguish the different processes on a server
and client. We know that UDP provides a process to process communication. The client
generates the processes that need services while the server generates the processes that
provide services. The queues are available for both the processes, i.e., two queues for
each process. The first queue is the incoming queue that receives the messages, and the
second one is the outgoing queue that sends the messages. The queue functions when
the process is running. If the process is terminated then the queue will also get
destroyed.

UDP handles the sending and receiving of the UDP packets with the help of the
following components:

o Input queue: The UDP packets uses a set of queues for each process.
o Input module: This module takes the user datagram from the IP, and then it
finds the information from the control block table of the same port. If it finds the
entry in the control block table with the same port as the user datagram, it
enqueues the data.
o Control Block Module: It manages the control block table.
o Control Block Table: The control block table contains the entry of open ports.
o Output module: The output module creates and sends the user datagram.

Several processes want to use the services of UDP. The UDP multiplexes and
demultiplexes the processes so that the multiple processes can run on a single host.

Limitations

o It provides an unreliable connection delivery service. It does not provide any


services of IP except that it provides process-to-process communication.
o The UDP message can be lost, delayed, duplicated, or can be out of order.
o It does not provide a reliable transport delivery service. It does not provide any
acknowledgment or flow control mechanism. However, it does provide error
control to some extent.

Advantages

o It produces a minimal number of overheads.


Connectionless (UDP) Sockets
Connectionless sockets (the User Datagram Protocol, or UDP) are your other option for transferring
data between two networked devices. These are typically used in applications that require little
overhead and that want to achieve higher network throughput, such as multimedia streaming
protocols. Another advantage in using UDP is that it is capable of transmitting data to multiple
endpoints simultaneously because a connection is not bound to a single address. Because UDP
transfers datagrams (message packets) instead of a connected stream, these connections are
considered unreliable and connectionless. However, don't mistake the term unreliable for low
quality?unreliable in this context means only that the protocol does not guarantee that your data
packets will ever arrive at your destination. Moreover, there is no sequenced order in which they are
guaranteed to arrive, nor any notification if a packet never arrives.
You can compare using UDP datagrams to checking in several pieces of luggage (your packets) at
the airport at the same time. Even though they boarded the plane in some order (the packets going
out over the network), you're pretty sure that they'll arrive at their destination. Once you get off the
plane and attempt to claim your luggage, you're not exactly sure what order they'll be unloaded in
(packets arriving at the endpoint), but you can be relatively certain that they'll get there in one piece.
Unfortunately, once in a while, something does get lost and never is seen again.
If you are planning to use UDP as your method to send data, it's probably a good idea to have your
application either send some sort of acknowledgment that it received a datagram, or provide some
way to reassemble packets in a predetermined order by using some sort of sequence?such as a
packet number or timestamp?in your datagram message. This can ensure some amount of reliability
with the protocol.
Figure 1.4 shows the process for creating both client and server UDP socket connections and how
data flows between both network endpoints.
Figure 1.4. Socket process for connectionless clients and servers

Before you can send or receive UDP packets, whether you are the client or the server, you need to
create a socket to talk to using the socket() function, and pass
the SOCK_DGRAM and IPPROTO_IDP parameters:

SOCKET sUDPSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

Once you have created your sockets, you also need to bind() the socket to the interface on which
you want to receive data. This is done exactly the same way as using a TCP connection.
Now that we have our sockets ready, let's take a look at what is required to both send and receive
datagram packets. Remember that even though we have bound the socket, we don't need to call
the listen() or accept() functions, as we are going to be operating in a connectionless manner,
which enables us to send or receive packets to any device on the network.

Sending a UDP Datagram


Once you have created your sockets, sending a packet over UDP is fairly straightforward. To send a
message, you need to call the sendto() function, which is defined as follows:

int sendto (SOCKET s, const char *buf, int len, int flags,
const struct sockaddr *to, int tolen);

You might notice that the parameters are similar to the send() function.


The s parameter is the socket on which we want to send data, which was created using
the socket() function. The buf parameter is a pointer to a buffer that contains the data we want to
send, and its length is specified in the len parameter. The flags parameter is used to affect the
way the data is sent, and can be 0 or MSG_DONTROUTE, which specifies that the data should not be
routed. Typically, this parameter will be set to 0. The to parameter contains a pointer to
a SOCKADDR_IN address structure with the packet's destination address. You can also construct a
broadcast packet (sending it to every machine on the network, which is usually not advised), and
you can use the address INADDR_BROADCAST if you have set the socket option to broadcast mode
(see the section "Socket Options"). Finally, the tolen parameter specifies the length of
the to address.
The sendto() function will return the number of bytes it has transferred, or a SOCKET_ERROR if there
was a problem sending the datagram.
The following example sends a UDP datagram:

// Create a connectionless socket


SOCKET sUDPSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

// Check to see if we have a valid socket


if(sUDPSocket == INVALID_SOCKET) {
int iSocketError = WSAGetLastError();
return FALSE;
}

// Set up the target device address. For this sample,


// we are assuming it is a machine at 192.168.0.1, and on
// port 40040
SOCKADDR_IN sTargetDevice;
memset(&sTargetDevice, 0, sizeof(SOCKADDR_IN));

sTargetDevice.sin_family = AF_INET;
sTargetDevice.sin_port = htons(40040);
sTargetDevice.sin_addr.s_addr = inet_addr("192.168.0.1");

// Send a datagram to the target device


char cBuffer[1024] = "Test Buffer";
int nBytesSent = 0;
int nBufSize = strlen(cBuffer);

nBytesSent = sendto(sUDPSocket, cBuffer, nBufSize, 0,


(SOCKADDR *) &sTargetDevice,
sizeof(SOCKADDR_IN));

// Close the socket


closesocket(sUDPSocket);

Receiving a UDP Datagram


To have your application receive a UDP packet, you need to call the recvfrom() function, which
will block until data has arrived from a client (or it can return immediately if in nonblocking mode; see
"Socket Options"):

int recvfrom (SOCKET s, char *buf, int len, int flags,


struct sockaddr *from, int *fromlen);

Notice that the parameters are very similar to those described for the recv() function. The first
parameter, s, is the socket on which we want to receive data. Next, buf is a pointer to a buffer for
the incoming data, and its size is specified by the len parameter. The flags parameter must be set
to 0. Finally, the from parameter contains a pointer to the SOCKADDR_IN structure, which contains
information about the device that sent the data. A pointer to its length is in the fromlen field.
If the packet is received successfully, recvfrom() will return a 0; otherwise, a SOCKET_ERROR will
occur.
The following example shows how to receive a UDP datagram packet:

// Create a connectionless socket


SOCKET sUDPSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

// Check to see if we have a valid socket


if(sUDPSocket == INVALID_SOCKET) {
int iSocketError = WSAGetLastError();
return FALSE;
}
// Setup a bind on the socket, telling us what port and
// adapter to receive datagrams on. Assume we are listening
// on port 40040
SOCKADDR_IN sReceiveFromAddr;
memset(&sReceiveFromAddr, 0, sizeof(SOCKADDR_IN));

sReceiveFromAddr.sin_family = AF_INET;
sReceiveFromAddr.sin_port = htons(40040);
sReceiveFromAddr.sin_addr.s_addr = htonl(INADDR_ANY);

if(bind(sUDPSocket, (SOCKADDR *)&sReceiveFromAddr,


sizeof(SOCKADDR_IN)) ==
SOCKET_ERROR) {
int iSocketError = WSAGetLastError();
return FALSE;
}

// Receive a datagram from another device


char cBuffer[1024] = "";
int nBytesRecv = 0;
int nBufSize = strlen(cBuffer);
int nReceiveAddrSize = 0;

// Get the datagram


nBytesRecv = recvfrom(sUDPSocket, cBuffer, nBufSize, 0,
(SOCKADDR *) &sReceiveFromAddr,
&nReceiveAddrSize);

// Close the socket


closesocket(sUDPSocket);
WSACleanup();

One final note regarding the sending and receiving of UDP data: You can also transfer data by using
the connect(), send(), and recv() functions. Transmitting UDP data this way is considered a
somewhat "directed" connectionless transfer, and should be used only if you plan to communicate
with one other device during a session (i.e., all packets are sent to the same address). To do this,
after your UDP socket has been created, call the connect() function with SOCKADDR_IN set to the
machine you want to establish a session with. No real connection will be established, but you can
use the send() and recv() functions to transfer data with the associated address.

What Is User Datagram


Protocol (UDP)?
Quick definition: User Datagram Protocol (UDP) is a
communications standard for exchanging data over the
Internet. UDP prioritizes speed over reliability, using a
connectionless process to send data packets to a
destination. Due to its low latency, UDP is ideal for time-
sensitive use cases like video streaming, Voice over
Internet Protocol (VoIP), video gaming, and Domain Name
System (DNS) lookups.
 
IOT GLOSSARY

Written by EMnify

SHARE THIS POST

When higher-level protocols need to transmit data quickly, they rely on UDP to
package and distribute that data over the Internet Protocol (IP).

Unlike Transmission Control Protocol (TCP)—the most common protocol used


for transmitting data over the Internet—UDP doesn’t order data packets or
directly establish a connection between the endpoints, such as an IoT security
camera and a smartphone. It also has no congestion control systems to
optimize network resources. It simply gets data from Endpoint A to Endpoint B
as quickly as possible.
When exchanging data over the Internet Protocol, data packets can often
arrive out of order or get lost in transmission. TCP will request retransmissions
of lost data packets and reorganize packets that arrive out of order. This
increases accuracy, but it also increases latency, and if individual packets of
an audio or video file get lost, humans often can’t even detect the errors.
Retransmitting missing packets or reordering them when they arrive will only
cause more interference in the real-time data stream. 

UDP doesn’t correct errors, duplicates, or missing pieces. If a protocol uses


UDP for transmitting data, data integrity is either unimportant, or the
application itself has a process for checking against errors.

UDP headers
Like TCP, UDP labels data packets with a header. But UDP headers are
much simpler. There are only four fields: 

1. Source port
2. Destination port
3. UDP length
4. Checksum
The source port indicates where the transmission is coming from. The
destination port indicates where it’s going. The UDP length specifies how
many bytes the header and data represent. And the checksum is a field
that can be used to check for errors in the header or data stream.

TCP has numerous additional fields in the header which help verify that the
data packets arrive intact and can be rearranged as needed. These additional
fields significantly increase the size of the header.
UDP in IoT
In IoT (and data transmission in general), User Datagram Protocol is less
common than TCP. But UDP often appeals to IoT manufacturers because it
uses fewer network resources to transmit and doesn’t have to maintain a
constant connection between the two endpoints. In other words, it uses less
data and consumes less power. 

Resource constrained devices


IoT devices often operate within Low power, Lossy Networks (LLNs). LLNs
are optimized for power efficiency, so they have very few resources.
Constrained Application Protocol (CoAP) was specifically developed to help
these devices communicate, and it runs on devices that use UDP.

Low downlink transmissions


UDP doesn’t send any acknowledgement that a transmission was received.
The sender doesn’t know if the data packets arrived, but the exchange
requires less downlink budget. For transmissions with low downlink
allowances, UDP can be a valuable communication protocol.

Low power applications


In IoT, it’s often not a problem to lose a single datapoint because the device
sends it periodically. Trying to resend the data drains more battery every time
a datapoint gets lost or has an error. And since UDP doesn’t send an
acknowledgement, the device can turn off faster after sending or receiving a
transmission. This makes UDP appealing for developers who want to
maximize power efficiency.

UDP security
While UDP is easy to implement and it has less overhead, it also leaves your
devices more vulnerable to cyber attacks.

Since TCP establishes a direct connection and provides a sequence number,


it’s more difficult for someone to send a packet to a specific application. With
UDP, it’s easier to intercept, alter, and replicate data packets to attack a
device, application, or network.

Additionally, botnets (massive networks of hacked computers, including IoT


devices) can use UDP to send fraudulent packets to a computer. Bots will
often spam transmissions to nonexistent ports, and the computer then has to
send a response that the port is unavailable. This quickly takes network
resources from legitimate data transmissions and can bring down the network.

With UDP, you need to be proactive about IoT security and be confident that


your hardware and network-level security can protect your customers’ data
and prevent your devices from becoming liabilities.

Get secure IoT connectivity with


EMnify
EMnify is a communication platform dedicated to IoT. Not only can your
devices connect through our global mobile network but the platform also
ensures the security of your device. With advanced security features like
private networks, network firewalls with IP whitelisting, and custom DNS we
prevent common UDP attacks and make malicious communication with your
device impossible.

User Datagram Protocol (UDP) :


It is a transport layer protocol. It is an unreliable and connectionless protocol. It
is much faster, simpler, and efficient than TCP. However, it doesn’t check errors
due to which Bandwidth is saved. It is widely used in real-time services like
videogame, voice, or video communication
The packets sent by the UDP are called user datagrams.
Services offered by the TCP are as follows :
 Process to Process port to port transmission of segments
 Connectionless and minimum overhead Protocol
 Fast and simple transmission
 No flow and error control, applications using UDP services are responsible
for providing them
 UDP encapsulates and decapsulates the messages.
Advantages :
 
 The packet created by UDP is relatively smaller than that of TCP(UDP
Header: 8 bytes)
 Connectionless Transmission
 It is Faster, Simpler and Efficient
Disadvantages : 
 There is no guarantee that the sender will receive the data
 Lack of proper Errochecking mechanisms
 The lost packets will not be retransmitted
 There is a possibility of receiving out of order packets
Real-Life Examples of UDP :
1. Online Games –
Most of the online games we play use the services of User Datagram
Protocol. Since any amount of delay cannot be tolerated in online games
UDP is widely used over TCP which is quite slower. UDP doesn’t retransmit
the lost data and is a connectionless protocol due to which it is much faster.
Ex : All online games
 
2. Video Conferencing –
Video Conferencing apps like Skype, Gmeet, Zoom, all use the services of
UDP due to the fact that they are real-time applications and any delay in
receiving the data cannot be tolerated.
Ex: Skype, Google Meet, zoom, and Facetime.
 
3. Voice Over IP(VoIP) –
It is similar to Video Conferencing, where apps like Viber, Whatsapp, Google
Hangouts use UDP for converting our voice to digital data and transmit it
over the network, hence the name VoIP.
Ex : Viber, Whatsapp Voice calling, Wi-Fi calling.
 
4. Domain Name System(DNS) –
It is a service used for mapping domain names to their corresponding IP
address. It is used by the application layer. It can also be looked at as a
distributed DataBase that has a hierarchical name Server. DNS uses UDP
for fetching the corresponding IP address due to the following reasons:
a) UDP is much faster than TCP. After all, speed matters a lot when loading
a webpage 
b) DNS requests are typically small requests and can be accommodated
inside UDP segments(Header).
c) Even though UDP is unreliable, it can be achieved in the application layer
too
Hence, these were the Real-Life Examples of TCP and UDP.
UDP - Client And Server Example
Programs In Python
  

1. Home
2. Modules
3. Socket
4. Udp-client-server-example

UDP Overview:
UDP is the abbreviation of User Datagram Protocol. UDP makes use of
Internet Protocol of the TCP/IP suit. In communications using UDP, a client
program sends a message packet to a destination server wherein the
destination server also runs on UDP.
Properties of UDP:
 The UDP does not provide guaranteed delivery of message packets. If
for some issue in a network if a packet is lost it could be lost forever.
 Since there is no guarantee of assured delivery of messages, UDP is
considered an unreliable protocol.
 The underlying mechanisms that implement UDP involve no connection-
based communication. There is no streaming of data between a UDP
server or and an UDP Client.
 An UDP client can send "n" number of distinct packets to an UDP server
and it could also receive "n" number of distinct packets as replies from
the UDP server.
 Since UDP is connectionless protocol the overhead involved in UDP is
less compared to a connection based protocol like TCP.
Example: UDP Server using Python
import socket
 
localIP     = "127.0.0.1"
localPort   = 20001
bufferSize  = 1024
 
msgFromServer       = "Hello UDP Client"
bytesToSend         = str.encode(msgFromServer)
 
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.
 
# Bind to address and ip
UDPServerSocket.bind((localIP, localPort))
 
print("UDP server up and listening")
 
# Listen for incoming datagrams
while(True):
    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
    message = bytesAddressPair[0]
    address = bytesAddressPair[1]
    clientMsg = "Message from Client:{}".format(message)
    clientIP  = "Client IP Address:{}".format(address)
    
    print(clientMsg)
    print(clientIP)
   
    # Sending a reply to client
    UDPServerSocket.sendto(bytesToSend, address)

Output:
UDP server up and listening
Message from Client:b"Hello UDP Server"
Client IP Address:("127.0.0.1", 51696)
 

Example: UDP Client using Python


import socket
 
msgFromClient       = "Hello UDP Server"
bytesToSend         = str.encode(msgFromClient)
serverAddressPort   = ("127.0.0.1", 20001)
bufferSize          = 1024
 
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.
 
# Send to server using created UDP socket
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
 
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
 
msg = "Message from Server {}".format(msgFromServer[0])
print(msg)
 
 
  Output:
 

Message from Server b"Hello UDP Client"


 
 

Drawbacks or disadvantages of UDP


Following are the drawbacks or disadvantages of UDP:
➨It is connectionless and unreliable transport protocol. There is no windowing
and no function to ensure data is received in the same order as it was
transmitted.
➨It does not use any error control. Hence if UDP detects any error in the
received packet, it silently drops it.
➨There is no congestion control. Hence large number of users transmitting lots
of data via UDP can cause congestion and no one can do anything about it.
➨There is no flow control and no acknowledgement for received data.
➨Only application layer deals with error recovery. Hence applications can simply
turn to the user to send the message again.
➨Routers can be careless with UDP. They do not retransmit a UDP datagram
after collision and will often discard UDP packets before TCP packets.

You might also like