The Wayback Machine - https://web.archive.org/web/20241006042321/https://www.geeksforgeeks.org/udp-server-client-implementation-c/
Open In App

UDP Server-Client implementation in C++

Last Updated : 23 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are two primary transport layer protocols to communicate between hosts: TCP and UDP. Creating TCP Server/Client was discussed in a previous post. 

Prerequisite: Creating TCP Server/Client

Theory: In UDP, the client does not form a connection with the server like in TCP and instead sends a datagram. Similarly, the server need not accept a connection and just waits for datagrams to arrive. Datagrams upon arrival contain the address of the sender which the server uses to send data to the correct client. 

The entire process can be broken down into the following steps : 

UDP Server :  

  1. Create a UDP socket.
  2. Bind the socket to the server address.
  3. Wait until the datagram packet arrives from the client.
  4. Process the datagram packet and send a reply to the client.
  5. Go back to Step 3.

UDP Client :  

  1. Create a UDP socket.
  2. Send a message to the server.
  3. Wait until a response from the server is received.
  4. Process the reply and go back to step 2, if necessary.
  5. Close socket descriptor and exit.

Necessary Functions :  

int socket(int domain, int type, int protocol)
Creates an unbound socket in the specified domain.
Returns socket file descriptor.

Arguments : 
domain – Specifies the communication 
domain ( AF_INET for IPv4/ AF_INET6 for IPv6 ) 
type – Type of socket to be created 
( SOCK_STREAM for TCP / SOCK_DGRAM for UDP ) 
protocol – Protocol to be used by the socket. 
0 means using the default protocol for the address family.  

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
Assigns address to the unbound socket.

Arguments : 
sockfd – File descriptor of a socket to be bonded 
addr – Structure in which the address to be bound to is specified 
addrlen – Size of addr structure  

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
               const struct sockaddr *dest_addr, socklen_t addrlen)
Send a message on the socket

Arguments : 
sockfd – File descriptor of the socket 
buf – Application buffer containing the data to be sent 
len – Size of buf application buffer 
flags – Bitwise OR of flags to modify socket behavior 
dest_addr – Structure containing the address of the destination 
addrlen – Size of dest_addr structure  

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                 struct sockaddr *src_addr, socklen_t *addrlen)
Receive a message from the socket.

Arguments : 
sockfd – File descriptor of the socket 
buf – Application buffer is a pointer which receives the data 
len – Size of buf application buffer 
flags – Bitwise OR of flags to modify socket behavior 
src_addr – Structure containing source address is returned 
addrlen – Variable in which the size of src_addr structure is returned 

int close(int fd)
Close a file descriptor

Arguments:

 fd – File descriptor

In the below code, the exchange of one hello message between the server and client is shown to demonstrate the model.

Filename: UDPServer.c++

C++14




// Server side implementation of UDP client-server model
#include <bits/stdc++.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
   
#define PORT     8080
#define MAXLINE 1024
   
// Driver code
int main() {
    int sockfd;
    char buffer[MAXLINE];
    const char *hello = "Hello from server";
    struct sockaddr_in servaddr, cliaddr;
       
    // Creating socket file descriptor
    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
       
    memset(&servaddr;, 0, sizeof(servaddr));
    memset(&cliaddr;, 0, sizeof(cliaddr));
       
    // Filling server information
    servaddr.sin_family    = AF_INET; // IPv4
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(PORT);
       
    // Bind the socket with the server address
    if ( bind(sockfd, (const struct sockaddr *)&servaddr;, 
            sizeof(servaddr)) < 0 )
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
       
    socklen_t len;
  int n;
   
    len = sizeof(cliaddr);  //len is value/result
   
    n = recvfrom(sockfd, (char *)buffer, MAXLINE, 
                MSG_WAITALL, ( struct sockaddr *) &cliaddr;,
                &len;);
    buffer[n] = '\0';
    printf("Client : %s\n", buffer);
    sendto(sockfd, (const char *)hello, strlen(hello), 
        MSG_CONFIRM, (const struct sockaddr *) &cliaddr;,
            len);
    std::cout<<"Hello message sent."<<std::endl; 
       
    return 0;
}


Filename: UDPClient.c++

C++14




// Client side implementation of UDP client-server model
#include <bits/stdc++.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
   
#define PORT     8080
#define MAXLINE 1024
   
// Driver code
int main() {
    int sockfd;
    char buffer[MAXLINE];
    const char *hello = "Hello from client";
    struct sockaddr_in     servaddr;
   
    // Creating socket file descriptor
    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
   
    memset(&servaddr;, 0, sizeof(servaddr));
       
    // Filling server information
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(PORT);
    servaddr.sin_addr.s_addr = INADDR_ANY;
       
    int n;
    socklen_t len;
       
    sendto(sockfd, (const char *)hello, strlen(hello),
        MSG_CONFIRM, (const struct sockaddr *) &servaddr;, 
            sizeof(servaddr));
    std::cout<<"Hello message sent."<<std::endl;
           
    n = recvfrom(sockfd, (char *)buffer, MAXLINE, 
                MSG_WAITALL, (struct sockaddr *) &servaddr;,
                &len;);
    buffer[n] = '\0';
    std::cout<<"Server :"<<buffer<<std::endl;
   
    close(sockfd);
    return 0;
}


Output : 

$ ./server
Client : Hello from client
Hello message sent.
$ ./client
Hello message sent.
Server : Hello from server


Similar Reads

UDP Client Server using connect | C implementation
UDP is a connection less protocol. There is no connection is established between client and server. Creating Standard UDP Client/Server is discussed here Prerequisite : Socket Programming in C/CPP | UDP server-client implementation In UDP, the client does not form a connection with the server like in TCP and instead, It just sends a datagram. Simil
3 min read
TCP Server-Client implementation in C
Prerequisites - Socket Programming in C/C++, TCP and UDP server using select, UDP Server-Client implementation in C If we are creating a connection between client and server using TCP then it has a few functionalities like, TCP is suited for applications that require high reliability, and transmission time is relatively less critical. It is used by
4 min read
Setting up local DNS server between client-server machines
In this, article you will see the overview of DNS server and how to set up the local DNS server between the client and server machines. And here we will use Wireshark. Let's discuss it one by one. Introduction :A DNS server is computer server that contains a database of public IP addresses and their associated hostname, and in most cases serves to
5 min read
Message encryption and decryption using UDP server
The process of message encryption and decryption during client-server communication using UDP server is as follows: The client requests the server with a file name.The corresponding file is opened by the server and sends the file using datagram socket.The sender sends the encrypted text (Xoring) with a fixed length key.The receiver receives the enc
3 min read
TCP and UDP server using select
Prerequisites: TCP UDP In previous articles, we have seen a TCP server and a UDP server. But now we can combine our concurrent TCP echo server and iterative UDP server into a single server that uses select to multiplex TCP and UDP socket. The Select function is used to select between TCP and UDP sockets. This function gives instructions to the kern
5 min read
How to create a multi-chat server using UDP?
In this article, we will see the development of a Multi-Threaded UDP Chat Server-Client Network for Data Transfer in Linux. UDP is used for low latency and connectionless characteristics, the architecture consists of a server managing multiple clients through threading. This networked chat application facilitates real-time communication, allowing u
10 min read
Reverse a string in C/C++ using Client Server model
This article describes a Client and Server setup where a Client connects, sends a string to server and the server shows the original string and sends reversed string to client using socket connection. Prerequisite : Socket Programming Examples: Input : welcome Output :emoclew Input :geeks for geeks Output :skeeg rof skeeg Explanation In this, first
3 min read
TCP Client-Server Program to Check if a Given String is Palindrome
Prerequisites: Socket Programming in C/C++, TCP and UDP server using select, UDP Server-Client implementation in C TCP Client-Server Implementation in C This article describes a Client and Server setup where a Client connects, sends a string to the server and the server shows the original string and sends confirmation whether the string is a palind
4 min read
Distributed Objects Computing: The next generation of client-server computing
Software technology is in the midst of a major computational shift towards distributed object computing DOC. Distributed computing is poised for a second client-server revolution, a transition from first generation client-server era to the next generation client-server era. In this new client-server model, servers are plentiful instead of scarce(be
2 min read
Simple client/server application in C
Overview :Create a simple client/server application in C using the concept of socket programming. Where server send some message to the client when getting connected. Client : In this section, the term ‘Client’ is defined and its socket workflow is explained in detail, through different functions used to implement the client. An application that ru
4 min read
What are the Two Broad Classes of Middleware in Client Server Environment?
Server: A server is a computer program that provides services, data, information to other computer programs. Client: A client is a host computer, requests services or information from the server. the client is also called a user. In a computer system, a client is a computer program that asks something from the server and the server gives the inform
5 min read
Difference Between Server OS and Client OS
Client Operating Systems and Server Operating Systems are two awesome sorts of operating systems designed to serve exclusive purposes inside a computer network surroundings. While each form of working system shares some similarities in phrases of basic functionalities, they're optimized for different use instances and feature particular functions t
7 min read
Difference between Client-Server and Peer-to-Peer Network
In the world of network architecture, two fundamental models are widely utilized to structure data exchange and resource sharing. For the purpose of this discussion, two types of networks are available; the Client-Server Network and the Peer-to-Peer Network. All the models have their strengths, weaknesses, and appropriate applications that make the
4 min read
Difference between Client side filter and Server side filters in Cyber Security
Filters are key components in web applications that validate user input and ensure it meets certain standards. These filters can be implemented on the client side (within the user's web browser) or the server side (on the web server). Understanding the differences between client-side and server-side filters is necessary to maintain data quality and
5 min read
Difference Between Client /Server and Distributed DBMS
In today's digital era, managing large volumes of data efficiently and effectively is very crucial for any organization. Here we have the requirement of a Database and to manage it we also require a management system. Two most popular database management systems are Client/Server DBMS and Distributed DBMS. Both aim to facilitate data storage, data
7 min read
C program for file Transfer using UDP
Data can be transferred between two computers using Socket programming in C. Similarly, files can easily be sent using UDP protocol and a simple client/server. Security: Handled by encryption. Protocol : UDP Encryption: XOR encryption Algorithm : 1. The server starts and waits for filename. 2. The client sends a filename. 3. The server receives fil
4 min read
TCP and UDP in Transport Layer
Layer 3 or the Network layer uses IP or Internet Protocol which being a connection less protocol treats every packet individually and separately leading to lack of reliability during a transmission. For example, when data is sent from one host to another, each packet may take a different path even if it belongs to the same session. This means the p
4 min read
Various TCP and UDP ports
Transportation layer conventions utilize the idea of ports and multiplexing/demultiplexing to convey information to individual services listening on network nodes. These ports are spoken to by a solitary 16-bit number, implying that they can constitute a range of numbers 0-65535. This range has been separated by the IANA (Internet Assigned Numbers
4 min read
Difference between SCTP and UDP
1. Stream Control Transmission Protocol (SCTP): SCTP is a connection-oriented protocol in computer networks that provides full-duplex association i.e., Transmitting multiple streams of data between two endpoints at the same time that have been established connection in the network. 2. User Datagram Protocol (UDP): UDP is a Transport Layer protocol.
2 min read
Difference between UDP and RTP
1. User Datagram Protocol (UDP) : UDP is a Transport Layer protocol. It is a part of Internet Protocol suite, referred as UDP/IP suite. It is unreliable and connection-less protocol. Hence, there is no need to establish connection prior to data transfer. UDP sockets are an example of datagram sockets. It is more efficient in multicasting and broadc
2 min read
Examples on UDP Header
User Datagram Protocol is a Transport Layer protocol. UDP is a part of the Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So, there is no need to establish a connection prior to data transfer. Though Transmission Control Protocol (TCP) is the dominant transport layer protocol used
4 min read
TCP vs UDP for Video Streaming
Prerequisite : TCP/IP Model, User Datagram Protocol (UDP)In this era of the modern internet with entertainment, education, gaming and all kinds of necessities streaming live everyday, the demand of an uninterrupted video stream is highly adamant. To dive into the topic of which protocol is better for video streaming, one must be familiar with the T
6 min read
Examples of TCP and UDP in Real Life
Today we will see the Real-Life Examples of TCP and UDP in Computer Networks Before looking at the Real-Life Examples of TCP and UDP, Let's see What is Computer Network? A Computer Network is a set of devices (Nodes) that are connected to each other by communication links to share digital information.The communication links can either be wireless m
8 min read
Why is YouTube using TCP but not UDP?
Overview :In this article, we will discuss about which technology YouTube uses for streaming videos and music on its platform. YouTube is an American online video sharing and web-based media stage by Google. It is most utilized sites in the entire world. YouTube is a free video-facilitating site that permits individuals to store and serve video con
3 min read
Why does Netflix use TCP but not UDP for streaming video?
Overview :In this article, we will discuss which technology Netflix uses for streaming online movies and web series on its platform. Netflix is an American subscription-based streaming service provider company. It is famous for streaming online videos, web series, and movies based on its subscription that its customers buy. There are two types of t
3 min read
UDP-Hunter - Network Assessment Tool
UDP-Hunter is a free and open-source tool available on GitHub. UDP-Hunter is written in python language. You must have python language installed in your kali Linux operating system in order to use the tool. UDP-Hunter is used for UDP scanning. UDP-Hunter scans all the UDP services on a network. UDP-Hunter is a tool that is used by red teamers and s
2 min read
How Applications Coexist Over TCP and UDP?
The Transport layer takes data from the Application layer, then it breaks into small segments called packets. Then handles them to the Network Layer for delivery. The transport layer uses two protocols which will be discussed here in this article. They are TCP ( Transmission Control Protocol ) and UDP ( User Datagram Protocol ). TCP ( Transmission
4 min read
Difference Between TCP, UDP and SCTP Protocols
In the realm of computer networking, different protocols play a vital role in facilitating the transmission of data across the internet. Three prominent protocols, TCP (Transmission Control Protocol), UDP (User Datagram Protocol), and SCTP (Stream Control Transmission Protocol), serve as the building blocks of modern network communication. Each of
6 min read
Using netcat to send a UDP packet without binding
Netcat, also known as nc, is a powerful networking tool used for various tasks, including sending data across networks using TCP or UDP protocols. It is a versatile tool with applications across network security, administration, and troubleshooting. This guide will specifically focus on using Netcat to send a UDP packet without binding to a local p
9 min read
Why does DNS use UDP and not TCP?
DNS is an application layer protocol. All application layer protocols use one of the two transport layer protocols, UDP and TCP. TCP is reliable and UDP is not reliable. DNS is supposed to be reliable, but it uses UDP, why? There are the following interesting facts about TCP and UDP on the transport layer that justify the above. 1) UDP is much fast
2 min read
Practice Tags :