- Sockets: Think of sockets as endpoints for network communication. They allow your program to connect to a network, send data, and receive data. Sockets have an address (IP address and port number) associated with them.
- IP Address: An IP address is a unique identifier for a device on a network. It's like a postal address for your computer on the internet. Examples include
127.0.0.1(localhost) and192.168.1.1(a typical address on a local network). - Port Number: A port number is a virtual point where network connections start and end. It's used to differentiate between different services running on the same machine. For example, port 80 is typically used for HTTP (web) traffic, and port 22 is used for SSH.
- Client-Server Model: This is a fundamental concept where a server provides services, and clients request those services. The server listens for incoming connections, and when a client connects, the server processes the request and sends back a response.
- TCP (Transmission Control Protocol): A reliable, connection-oriented protocol that ensures data is delivered in order and without errors. It's commonly used for applications like web browsing and email.
Hey guys! Today, we're diving into creating a daytime client-server program using C. This is a classic example that helps illustrate the basics of network programming, and it’s super useful for understanding how clients and servers communicate. Let's break it down step by step!
Understanding the Daytime Service
Before we get into the code, let's quickly understand what the daytime service is all about. The daytime service is a simple network service that provides the current date and time to any client that connects to it. It operates on a specific port (usually port 13) and is one of the oldest services on the internet. Its simplicity makes it an excellent starting point for learning network programming. Basically, a client connects to the server, the server sends back a string containing the current date and time, and the client displays that information. It's straightforward and perfect for beginners.
Why Use C for Network Programming?
You might be wondering, why C? Well, C provides a low-level control over system resources, which is crucial for network programming. It allows you to work directly with sockets and network protocols, giving you a deeper understanding of what's happening under the hood. Plus, C is known for its efficiency and performance, making it suitable for building robust and scalable network applications. While there are other languages you could use, C remains a popular choice due to its performance characteristics and the level of control it offers. This control is especially important when you're dealing with network operations where every bit of efficiency counts.
Basic Concepts in Network Programming
Before we jump into the code, let's cover some essential concepts in network programming. You'll need to understand these to grasp what's going on in the program:
Setting Up the Server
Alright, let's start with the server-side code. The server will listen for incoming connections on a specific port and send the current date and time to any client that connects. Here's 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 now;
char *time_string;
// 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);
while (1) {
// Accepting a new connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Get current time
now = time(NULL);
time_string = ctime(&now);
// Sending the time to the client
send(new_socket, time_string, strlen(time_string), 0);
printf("Sent: %s", time_string);
// Closing the connection
close(new_socket);
}
return 0;
}
Code Breakdown: Server
Let's break down what this code does:
- Includes: We include necessary header files for socket programming, string manipulation, time functions, and standard input/output.
- Socket Creation:
socket(AF_INET, SOCK_STREAM, 0)creates a new socket.AF_INETspecifies the IPv4 address family,SOCK_STREAMspecifies a TCP socket, and0is the protocol (IP). - Address Configuration: We set up the server address.
address.sin_family = AF_INETsets the address family to IPv4.address.sin_addr.s_addr = INADDR_ANYallows the server to listen on all available network interfaces.address.sin_port = htons(PORT)sets the port number. - Binding:
bind(server_fd, (struct sockaddr *)&address, sizeof(address))binds the socket to the specified address and port. This associates the socket with a specific IP address and port number, so it can listen for incoming connections. - Listening:
listen(server_fd, 3)puts the socket in a listening state, waiting for incoming connections. The3specifies the maximum number of queued connections. - Accepting Connections:
accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)accepts a new connection. This function blocks until a client tries to connect, and then it returns a new socket file descriptor for the new connection. - Getting the Time:
now = time(NULL)gets the current time.time_string = ctime(&now)converts the time to a human-readable string. - Sending the Time:
send(new_socket, time_string, strlen(time_string), 0)sends the time string to the client. - Closing the Connection:
close(new_socket)closes the connection with the client. It's important to close the socket to free up resources.
Compilation
To compile the server code, save it as server.c and use the following command:
gcc server.c -o server
Setting Up the Client
Now, let's create the client-side code. The client will connect to the server, receive the date and time, and display it. 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 sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
// Creating socket file descriptor
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(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("\nInvalid address/ Address not supported \n");
return -1;
}
// Connecting to the server
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
// Reading the time from the server
valread = read(sock, buffer, 1024);
printf("Time from server: %s\n", buffer);
return 0;
}
Code Breakdown: Client
Here’s what the client code does:
- Includes: We include necessary header files for socket programming, string manipulation, and standard input/output.
- Socket Creation:
socket(AF_INET, SOCK_STREAM, 0)creates a new socket, just like in the server code. - Address Configuration: We set up the server address.
serv_addr.sin_family = AF_INETsets the address family to IPv4.serv_addr.sin_port = htons(PORT)sets the port number. `inet_pton(AF_INET,
Lastest News
-
-
Related News
Latest Hindi News On Pseudodisease: Updates & Insights
Alex Braham - Nov 12, 2025 54 Views -
Related News
Benfica Vs. Tondela: Match Analysis And Predictions
Alex Braham - Nov 9, 2025 51 Views -
Related News
New American Standard Bible: Free Access & Resources
Alex Braham - Nov 12, 2025 52 Views -
Related News
GCam Nikita For Vivo Y19: Your Download And Setup Guide
Alex Braham - Nov 13, 2025 55 Views -
Related News
Safra Asset: Maximize Daily Returns
Alex Braham - Nov 13, 2025 35 Views