- Server Setup: The server creates a socket, binds it to a specific address and port, and then listens for incoming connections.
- Client Connection: The client creates a socket and attempts to connect to the server's address and port.
- Data Exchange: Once the connection is established, the client sends a request to the server (in our case, implicitly requesting the daytime). The server processes the request and sends the daytime information back to the client.
- Connection Closure: After the data is exchanged, both the client and server close their sockets to terminate the connection.
Let's dive into creating a daytime client-server program in C. This project is a fantastic way to understand the fundamentals of network programming, and it’s simpler than you might think! We’ll break down the code, explain the concepts, and get you up and running with a working example. So, grab your favorite text editor, and let’s get started!
Understanding the Basics
Before we jump into the code, it’s essential to grasp the basic concepts behind client-server architecture and network programming in C. The client-server model is a distributed application structure that divides tasks between a service provider (the server) and a service requester (the client). Think of it like a restaurant: the kitchen (server) prepares the food, and the waiter (client) brings it to your table.
In our case, the server will be responsible for providing the current date and time. The client will connect to the server and request this information. The server then sends the daytime information back to the client. Sounds simple, right? It is!
To achieve this in C, we'll use sockets. Sockets are endpoints in a network that allow us to send and receive data. They are the fundamental building blocks for network communication. We’ll be using the TCP (Transmission Control Protocol) for reliable, connection-oriented communication. TCP ensures that the data sent from the server arrives at the client in the correct order and without errors.
The key steps involved in setting up a client-server communication are as follows:
Server-Side Code
Let's start by creating the server-side code. This is where the magic happens. The server listens for incoming connections and provides the current date and time to any client that connects. Here's a breakdown of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 13 // Daytime port
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
time_t rawtime;
struct tm *timeinfo;
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Binding the socket to the specified address and port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listening for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d\n", PORT);
// Accepting incoming connections in a loop
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Get current time
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
// Send the time to the client
send(new_socket, buffer, strlen(buffer), 0);
printf("Sent daytime to client: %s\n", buffer);
// Closing the connected socket
close(new_socket);
}
return 0;
}
Code Explanation:
- Include Headers: We include necessary header files for socket programming, input/output, and time functions.
- Define Port: We define the port number that the server will listen on. The daytime service traditionally uses port 13, but you can use any available port.
- Create Socket: The
socket()function creates a new socket file descriptor.AF_INETspecifies the IPv4 address family, andSOCK_STREAMspecifies a TCP socket. - Bind Socket: The
bind()function assigns the socket to a specific address and port.INADDR_ANYallows the server to listen on all available network interfaces. - Listen for Connections: The
listen()function puts the socket in a listening state, waiting for incoming connections. The3argument specifies the maximum length of the queue for pending connections. - Accept Connections: The
accept()function accepts an incoming connection, creating a new socket for communication with the client. This happens in an infinite loop, allowing the server to handle multiple clients. - Get Current Time: The
time()andlocaltime()functions are used to get the current time. Thestrftime()function formats the time into a human-readable string. - Send Time to Client: The
send()function sends the formatted time string to the client. - Close Socket: The
close()function closes the socket, terminating the connection with the client.
Client-Side Code
Now, let's create the client-side code. The client connects to the server and receives the current date and time. Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 13 // Daytime port
int main(int argc, char const *argv[]) {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
// Creating socket file descriptor
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
printf("Invalid address/ Address not supported \n");
return -1;
}
// Connecting to the server
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("Connection Failed \n");
return -1;
}
// Reading the daytime from the server
read(sock, buffer, 1024);
printf("Daytime from server: %s\n", buffer);
// Closing the socket
close(sock);
return 0;
}
Code Explanation:
- Include Headers: We include necessary header files for socket programming and input/output.
- Define Port: We define the port number that the client will connect to. This should be the same as the server's port.
- Create Socket: The
socket()function creates a new socket file descriptor. - Set Server Address: We set the server address and port.
inet_pton()converts the IP address from text to binary form. Here, we use "127.0.0.1", which is the loopback address (localhost). - Connect to Server: The
connect()function attempts to establish a connection to the server. - Read Daytime: The
read()function reads the daytime information sent by the server. - Print Daytime: We print the received daytime information to the console.
- Close Socket: The
close()function closes the socket, terminating the connection.
Compiling and Running the Code
To compile the code, you'll need a C compiler like GCC. Save the server code as server.c and the client code as client.c. Then, open a terminal and navigate to the directory where you saved the files.
Compile the server code using the following command:
gcc server.c -o server
Compile the client code using the following command:
gcc client.c -o client
After compiling, you can run the server in one terminal window:
./server
And then run the client in another terminal window:
./client
You should see the server print "Server listening on port 13" and then "Sent daytime to client: YYYY-MM-DD HH:MM:SS" when a client connects. The client will print "Daytime from server: YYYY-MM-DD HH:MM:SS", where YYYY-MM-DD HH:MM:SS is the current date and time.
Key Improvements and Considerations
- Error Handling: The code includes basic error handling, but you can add more robust error checking to handle various failure scenarios.
- Port Selection: While port 13 is the traditional daytime port, it may require root privileges on some systems. You can use a higher, non-privileged port (e.g., 8080) for testing.
- Concurrency: The server is single-threaded, meaning it can only handle one client at a time. For a more robust server, you can use threads or processes to handle multiple clients concurrently.
- Security: This is a very basic example and doesn't include any security measures. In a real-world application, you'd need to consider security aspects such as authentication, encryption, and input validation.
- Non-blocking Sockets: For more advanced scenarios, you can use non-blocking sockets to handle multiple connections without blocking the main thread.
Conclusion
Creating a daytime client-server program in C is a great way to learn about network programming. This simple example demonstrates the basic concepts of sockets, client-server architecture, and data exchange. By understanding this foundation, you can build more complex and sophisticated network applications. So keep experimenting, keep coding, and keep learning! You've got this!
Lastest News
-
-
Related News
Pseinepalse Vs UAE Hong Kong Sixes: Who Will Win?
Alex Braham - Nov 9, 2025 49 Views -
Related News
Sports: Everything You Need To Know
Alex Braham - Nov 13, 2025 35 Views -
Related News
Free AUTOSAR Configuration Tools Available
Alex Braham - Nov 13, 2025 42 Views -
Related News
Puerto Rico Vs. Dominican Republic: Volleyball Showdown
Alex Braham - Nov 9, 2025 55 Views -
Related News
Inspirasi Nama Bayi Perempuan India: Modern & Cantik!
Alex Braham - Nov 9, 2025 53 Views