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

CSL 332 Networking Lab KTU 2019 Scheme - Dr Binu V P

CSL 332 Networking Lab KTU BTech 2019 Scheme About Me Scheme Syllabus Experiments 1.Learn the Networking Commands and Network Configuration Files     Basic networking commands     More Networking commands     Network configuration Files     View the configuration and address of your network interface     Network Connectivity      View Active TCP connections     MAC address of another machine using ARP  2.  System calls in Network Programming 3.  Simple TCP/IP Client Server Program 4.  Simple UDP Client Server Program 5.Application Programs     Concurrent UDP Time Server     Checking Prime Numbers 6. Simulate ARQ Protocols  / sliding window protocols          Stop and Wait           Go-Back-N          Selective Repeat  7. Routing Protocols - Distance Vector and Link State   ...

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...

Stop and Wait ARQ

Here's a simple C program that demonstrates the Stop-and-Wait ARQ protocol. This basic implementation simulates the sender transmitting packets one at a time and waiting for an acknowledgment from the receiver. If the acknowledgment is not received, the sender retransmits the packet. Key Points: The sender sends one packet at a time. If the receiver acknowledges it (ACK), the sender sends the next packet. If the acknowledgment is lost, the sender retransmits after a timeout. C Program: Stop-and-Wait ARQ Simulation #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h>  // for sleep() #define TIMEOUT 3  // Timeout duration in seconds #define TOTAL_PACKETS 5  // Number of packets to send int simulate_acknowledgment() {     // Simulate a 70% chance of successful acknowledgment     return rand() % 10 < 7; } int main() {     srand(time(0));  // Seed for random number generation     i...