Let's dive into creating a daytime client-server program in C. This guide will walk you through the process step-by-step, explaining each part so you can understand how it works and even customize it. Whether you're a beginner or an experienced programmer, understanding client-server models is crucial. So, grab your favorite text editor, and let's get started!
Understanding the Daytime Service
Before we jump into the code, let's quickly grasp what the “daytime service” actually does. Basically, it's a very simple network service that returns the current date and time as a human-readable string. It operates, by default, on TCP port 13. When a client connects to a daytime server, the server sends back the current date and time and then closes the connection. No fancy stuff, just a straightforward time announcement! This simplicity makes it perfect for learning about client-server communication.
Why is the Daytime Service Useful?
You might wonder, in our age of sophisticated APIs and time protocols, why bother with the daytime service? Well, it's incredibly useful for educational purposes. It provides a minimal example of how client-server interactions work over a network. It abstracts away a lot of the complexities you'd find in more elaborate systems, allowing you to focus on the fundamental concepts of socket programming, network connections, and basic data transfer. Plus, it's a fun little project to get your hands dirty with network programming in C!
Setting Up the Server
Alright, let’s start building our daytime server. This is the program that will listen for incoming connections and send back the time. We'll break it down into smaller, manageable parts. First, we need to include the necessary header files. These headers provide access to the functions and data structures we'll use for socket programming.
Include Necessary Headers
At the top of your C file, add the following lines:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
stdio.h: For standard input and output functions likeprintf.stdlib.h: For general utility functions likeexit.string.h: For string manipulation functions likestrcpy.time.h: For time-related functions liketimeandctime.sys/socket.h: For socket programming functions.netinet/in.h: For internet protocol family addresses.unistd.h: For miscellaneous symbolic constants and functions likeclose.
Creating the Socket
Next, we need to create a socket. A socket is an endpoint for communication between two processes, in this case, our client and server. We'll use the socket() function to create it. We need to specify the domain, type, and protocol. For our daytime server, we'll use the internet domain (AF_INET), a stream socket (SOCK_STREAM) for TCP, and the default protocol (0).
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
This code creates the socket and checks for errors. If socket() returns 0, it means there was an error creating the socket, and the program exits.
Binding the Socket
Now that we have a socket, we need to bind it to a specific address and port. This tells the operating system that our server is listening on that address and port for incoming connections. We'll use the bind() function for this.
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(13);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
Here's what's happening in this code:
- We create a
sockaddr_instructure to hold the address information. sin_familyis set toAF_INETto indicate the internet domain.sin_addr.s_addris set toINADDR_ANY, which means the server will listen on all available network interfaces.sin_portis set tohtons(13), which specifies port 13 for the daytime service.htons()converts the port number from host byte order to network byte order.- We call
bind()to bind the socket to the address. Ifbind()returns a value less than 0, it means there was an error, and the program exits.
Listening for Connections
With the socket bound to an address and port, we can now start listening for incoming connections. We'll use the listen() function for this. The listen() function puts the socket in a passive mode, where it waits for client connections.
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
The second argument to listen() specifies the maximum number of pending connections that can be queued up. In this case, we're allowing a maximum of 3 pending connections.
Accepting Connections
When a client tries to connect to our server, we need to accept the connection. We'll use the accept() function for this. The accept() function creates a new socket for the connection and returns the file descriptor for the new socket.
int addrlen = sizeof(address);
int new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
if (new_socket < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
Here, accept() waits for an incoming connection, and when it arrives, it returns a new socket file descriptor (new_socket) that is connected to the client. The original server_fd remains open and continues to listen for more connections.
Sending the Daytime
Now that we have a connection, we can send the current date and time to the client. We'll use the time() and ctime() functions to get the current time, and then use the send() function to send it to the client.
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime(buffer,sizeof(buffer),"%Y-%m-%d %H:%M:%S",timeinfo);
send(new_socket, buffer, strlen(buffer), 0);
printf("Daytime sent to client\n");
In this code:
- We declare a
time_tvariable to store the current time. - We get the current time using the
time()function. - We convert the time to a human-readable string using the
ctime()function. - We send the string to the client using the
send()function.
Closing the Connection
After sending the daytime, we need to close the connection. We'll use the close() function for this.
close(new_socket);
This closes the socket associated with the client connection, freeing up resources.
Putting It All Together: The Server Code
Here's the complete code for the daytime server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
// 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(13);
// Binding the socket to the port 13
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listening for connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// Accepting incoming connections
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Sending the current date and time
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime(buffer,sizeof(buffer),"%Y-%m-%d %H:%M:%S",timeinfo);
send(new_socket, buffer, strlen(buffer), 0);
printf("Daytime sent to client\n");
// Closing the connection
close(new_socket);
close(server_fd);
return 0;
}
Save this code in a file named daytime_server.c. To compile, use the following command:
gcc daytime_server.c -o daytime_server
Then, run the executable:
./daytime_server
Creating the Client
Now that we have a server, let's create a client to connect to it and receive the daytime. The client code is simpler than the server code, as it only needs to connect to the server and receive the data.
Include Necessary Headers
Just like the server, we need to include the necessary header files at the beginning of our client program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
These headers are similar to the ones we used in the server, with the addition of arpa/inet.h, which provides functions for converting between human-readable IP addresses and binary representations.
Creating the Socket
We create a socket in the client just like we did in the server, using the socket() function.
int sock = 0;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
Connecting to the Server
To connect to the server, we need to specify the server's address and port. We'll use the connect() function for this.
struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(13);
// 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("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
In this code:
- We create a
sockaddr_instructure to hold the server's address information. sin_familyis set toAF_INETto indicate the internet domain.sin_portis set tohtons(13), which specifies port 13 for the daytime service.inet_pton()converts the IP address from text format ("127.0.0.1" for localhost) to binary format.- We call
connect()to connect to the server. Ifconnect()returns a value less than 0, it means the connection failed.
Receiving the Daytime
Once the connection is established, we can receive the daytime from the server. We'll use the recv() function for this.
char buffer[1024] = {0};
recv(sock, buffer, sizeof(buffer), 0);
printf("Daytime: %s\n", buffer);
This code receives data from the server and stores it in the buffer. The recv() function returns the number of bytes received, or -1 if there was an error.
Closing the Connection
After receiving the daytime, we need to close the connection. We'll use the close() function for this.
close(sock);
Putting It All Together: The Client Code
Here's the complete code for the daytime client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(13);
// 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("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
recv(sock, buffer, sizeof(buffer), 0);
printf("Daytime: %s\n", buffer);
close(sock);
return 0;
}
Save this code in a file named daytime_client.c. Compile it using the following command:
gcc daytime_client.c -o daytime_client
Testing the Program
To test the program, first run the server in one terminal:
./daytime_server
Then, run the client in another terminal:
./daytime_client
The client should connect to the server and display the current date and time.
Conclusion
Congratulations! You've created a simple daytime client-server program in C. This example demonstrates the basic concepts of socket programming and client-server communication. You can expand on this example to create more complex network applications.
Lastest News
-
-
Related News
FNF Vs Animation: Download Guide For Android
Alex Braham - Nov 12, 2025 44 Views -
Related News
Zayn Malik Dan Istrinya: Perjalanan Cinta Dan Karier
Alex Braham - Nov 9, 2025 52 Views -
Related News
Alexander Zverev's Dad: Everything You Need To Know
Alex Braham - Nov 9, 2025 51 Views -
Related News
Mastering SEO & Monetization For E-commerce Success
Alex Braham - Nov 12, 2025 51 Views -
Related News
Difusi Vs. Osmosis: Perbedaan & Contoh Yang Mudah Dipahami!
Alex Braham - Nov 13, 2025 59 Views