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()
.
- Creates a UDP socket and binds to port
Client:
- Sends a message to the server using
sendto()
. - Waits for the server’s response with
recvfrom()
.
- Sends a message to the server using
How to Run the Programs:
- Compile the Server and Client:
- Start the Server:
- Run the Client (in another terminal):
Expected Output:
Server Terminal:
Client Terminal:
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
stdio.h
– For basic input/output functions likeprintf()
.string.h
– For string functions likestrlen()
.stdlib.h
– For standard functions likeexit()
.unistd.h
– For system calls likeclose()
.arpa/inet.h
– For socket-related functions and structures.
2. Variable Declaration
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
AF_INET
– Use IPv4 addresses.SOCK_DGRAM
– Create a UDP socket.0
– Protocol is automatically chosen (UDP forSOCK_DGRAM
).- Returns – A socket file descriptor. If it returns
-1
, the socket creation failed.
4. Server Address Setup
sin_family
– Set toAF_INET
for IPv4.sin_addr.s_addr
– UseINADDR_ANY
to accept data from any IP.sin_port
– The port is set to8080
(converted to network byte order byhtons()
).
5. Bind the Socket to the Address
bind()
– Associates the socket with the specified IP and port.(struct sockaddr *)&server
– Casts the server address structure tosockaddr
.- If
bind()
fails (returns-1
), the port may already be in use.
6. Wait for Data from Client
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
displays the message received from the client.
8. Respond to Client
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()
closes the socket and releases the resources.
UDP Client Breakdown (udp_client.c
)
1. Include Headers and Declare Variables
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
- Same as in the server, this creates a UDP socket.
3. Server Address Setup
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()
sends the message to the server.
5. Receive Response from Server
recvfrom()
waits for the server’s response and stores it inresponse
.
6. Close the Socket
- This closes the socket after communication ends.
Key Differences Between UDP and TCP:
- Connectionless – No connection establishment (
connect()
oraccept()
) is needed. - No Reliability – UDP doesn’t guarantee message delivery or order.
- Fast and Lightweight – Suitable for real-time applications like video streaming.
Comments
Post a Comment