Skip to main content

Client Server Communication using UDP

Here's a simple UDP client-server program in C. Unlike TCP, UDP is connectionless, meaning the server doesn't need to accept connections – it just waits for data and responds.

UDP Server (udp_server.c):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>

int main() {
    int sockfd;
    struct sockaddr_in server, client;
    char buffer[1024];
    socklen_t len = sizeof(client);

    // Create UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    // Server address configuration
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(8080);

    // Bind the socket to the server address
    bind(sockfd, (struct sockaddr *)&server, sizeof(server));

    printf("Waiting for data...\n");

    // Receive data from client
    recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &len);
    printf("Message from client: %s\n", buffer);

    // Respond to client
    sendto(sockfd, "Hello from server", 18, 0, (struct sockaddr *)&client, len);

    close(sockfd);
    return 0;
}

UDP Client (udp_client.c):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>

int main() {
    int sockfd;
    struct sockaddr_in server;
    char buffer[1024] = "Hello from client";
    char response[1024];
    socklen_t len = sizeof(server);

    // Create UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    // Server address configuration
    server.sin_family = AF_INET;
    server.sin_port = htons(8080);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");  // Server IP address

    // Send message to server
    sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&server, len);
    printf("Message sent to server\n");

    // Receive response from server
    recvfrom(sockfd, response, sizeof(response), 0, (struct sockaddr *)&server, &len);
    printf("Message from server: %s\n", response);

    close(sockfd);
    return 0;
}

How the Program Works:

  • Server:

    • Creates a UDP socket and binds to port 8080.
    • Waits for data using recvfrom().
    • Responds using sendto().
  • Client:

    • Sends a message to the server using sendto().
    • Waits for the server’s response with recvfrom().

How to Run the Programs:

  1. Compile the Server and Client:

    gcc udp_server.c -o udp_server gcc udp_client.c -o udp_client
  2. Start the Server:

    ./udp_server
  3. Run the Client (in another terminal):

    ./udp_client

Expected Output:

Server Terminal:


Waiting for data... Message from client: Hello from client

Client Terminal:


Message sent to server Message from server: Hello from server

Notes:

  • No Connection Setup: UDP is faster as there is no connection setup overhead.
  • Message Loss: UDP doesn’t guarantee message delivery, so some packets might get lost.
  • Multiple Clients: This setup can easily handle multiple clients without extra threading or forking

UDP Server Breakdown (udp_server.c)

1. Include Necessary Headers

#include <stdio.h>
#include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h>
  • stdio.h – For basic input/output functions like printf().
  • string.h – For string functions like strlen().
  • stdlib.h – For standard functions like exit().
  • unistd.h – For system calls like close().
  • arpa/inet.h – For socket-related functions and structures.

2. Variable Declaration

int sockfd;
struct sockaddr_in server, client; char buffer[1024]; socklen_t len = sizeof(client);
  • sockfd – The socket descriptor for the server.
  • sockaddr_in server, client – Structures to hold server and client addresses.
  • buffer[1024] – A buffer to store messages received from the client.
  • socklen_t len – Stores the size of the client address.

3. Create a UDP Socket

sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  • AF_INET – Use IPv4 addresses.
  • SOCK_DGRAM – Create a UDP socket.
  • 0 – Protocol is automatically chosen (UDP for SOCK_DGRAM).
  • Returns – A socket file descriptor. If it returns -1, the socket creation failed.

4. Server Address Setup

server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(8080);
  • sin_family – Set to AF_INET for IPv4.
  • sin_addr.s_addr – Use INADDR_ANY to accept data from any IP.
  • sin_port – The port is set to 8080 (converted to network byte order by htons()).

5. Bind the Socket to the Address


bind(sockfd, (struct sockaddr *)&server, sizeof(server));
  • bind() – Associates the socket with the specified IP and port.
  • (struct sockaddr *)&server – Casts the server address structure to sockaddr.
  • If bind() fails (returns -1), the port may already be in use.

6. Wait for Data from Client

printf("Waiting for data...\n");
recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &len);
  • recvfrom() – Waits for a message from the client.
  • Parameters:
    • sockfd – The socket descriptor.
    • buffer – Where to store incoming data.
    • sizeof(buffer) – Maximum size to receive.
    • 0 – No special flags.
    • (struct sockaddr *)&client – Fills the client’s address.
    • &len – Length of the client’s address.

7. Display the Message


printf("Message from client: %s\n", buffer);
  • printf displays the message received from the client.

8. Respond to Client

sendto(sockfd, "Hello from server", 17, 0, (struct sockaddr *)&client, len);
  • sendto() – Sends a message to the client.
  • Parameters:
    • sockfd – The socket descriptor.
    • "Hello from server" – The response message.
    • 17 – Length of the message.
    • 0 – No special flags.
    • (struct sockaddr *)&client – Address of the client to send to.
    • len – Size of the client address.

9. Close the Socket

close(sockfd);
  • close() closes the socket and releases the resources.

UDP Client Breakdown (udp_client.c)

1. Include Headers and Declare Variables

#include <stdio.h>
#include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> int sockfd; struct sockaddr_in server; char buffer[1024] = "Hello from client"; char response[1024]; socklen_t len = sizeof(server);
  • sockfd – Client socket descriptor.
  • sockaddr_in server – Server address structure.
  • buffer – Message to send to the server.
  • response – Stores the server’s response.

2. Create a UDP Socket

sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  • Same as in the server, this creates a UDP socket.

3. Server Address Setup

server.sin_family = AF_INET;
server.sin_port = htons(8080); server.sin_addr.s_addr = inet_addr("127.0.0.1");
  • inet_addr("127.0.0.1") – Converts the IP address to binary format.
  • This specifies that the client will communicate with a server running on the same machine (localhost).

4. Send Data to Server

sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&server, len);
printf("Message sent to server\n");
  • sendto() sends the message to the server.

5. Receive Response from Server

recvfrom(sockfd, response, sizeof(response), 0, (struct sockaddr *)&server, &len);
printf("Message from server: %s\n", response);
  • recvfrom() waits for the server’s response and stores it in response.

6. Close the Socket


close(sockfd);
  • This closes the socket after communication ends.

Key Differences Between UDP and TCP:

  • Connectionless – No connection establishment (connect() or accept()) is needed.
  • No Reliability – UDP doesn’t guarantee message delivery or order.
  • Fast and Lightweight – Suitable for real-time applications like video streaming.

Comments

Popular posts from this blog

Server/Client Communication-python

The basic mechanisms of client-server setup are: A client app send a request to a server app.  The server app returns a reply.  Some of the basic data communications between client and server are: File transfer - sends name and gets a file.  Web page - sends url and gets a page.  Echo - sends a message and gets it back.  Client server communication uses socket.              To connect to another machine, we need a socket connection. What's a connection?  A relationship between two machines, where two pieces of software know about each other. Those two pieces of software know how to communicate with each other. In other words, they know how to send bits to each other. A socket connection means the two machines have information about each other, including network location (IP address) and TCP port. (If we can use anology, IP address is the phone number and the TCP port is the extension).  A so...

Banker's Algorithm

Banker's algorithm is a deadlock avoidance algorithm. It is named so because this algorithm is used in banking systems to determine whether a loan can be granted or not. Consider there are n account holders in a bank and the sum of the money in all of their accounts is S. Everytime a loan has to be granted by the bank, it subtracts the loan amount from the total money the bank has. Then it checks if that difference is greater than S. It is done because, only then, the bank would have enough money even if all the n account holders draw all their money at once. Banker's algorithm works in a similar way in computers. Whenever a new process is created, it must exactly specify the maximum instances of each resource type that it needs. Let us assume that there are n processes and m resource types. Some data structures are used to implement the banker's algorithm. They are: Available: It is an array of length m . It represents the number of available resourc...

Inter Process Communication-Message Queue

Interprocess communication (IPC) is a set of programming interfaces that allow a programmer to coordinate activities among different program processes that can run concurrently in an operating system. This allows a program to handle many user requests at the same time. Since even a single user request may result in multiple processes running in the operating system on the user's behalf, the processes need to communicate with each other. The IPC interfaces make this possible. Each IPC method has its own advantages and limitations so it is not unusual for a single program to use all of the IPC methods . Message Based Communication Messages are a very general form of communication. Messages can be used to send and receive formatted data streams between arbitrary processes. Messages may have types. This helps in message interpretation. The type may specify appropriate permissions for processes. Usually at the receiver end, messages are put in a queue. Messages may also be fo...