Client-server program in C
In this article, we will discuss the client-server program in C with its example and benefits.
A client-server program in C is a network application that shows how two different programs operating on various devices connected over a network can communicate. The client is responsible for submitting requests to the server, which processes them and returns results to the client. With the help of this design, distributed computing is possible, allowing clients and servers to coexist peacefully on several computers.
Client:
This section defines the term "Client" and details how the client's socket workflow works using various functions. It is a computer program that is executed on a personal computer. Although it features a large and attractive user interface, it lacks any data the user can interact with or be shown. When a user 'asks' for anything, the client application connects to the server application to get what they want. The user is given the data in a pleasing format once it has been obtained. Typically, a client only talks to one user and receives data from one server at a time.
Workflow of Client:
The socket must be created as the first step in any socket programming.
- A socket() function call creates the client socket. The integer output of the socket() method. We specify the following parameters in the socket call.
- IPv4 domain (AF_INET)
- TCP/UDP (SOCK_STREAM) socket type
- IP protocol(0)
- The connect() method establishes a connection to a remote address. Here, we give the IP address and port information for the connection. A value is returned in the case of a successful connection.
- A recv() call is used to obtain the data. Both a file and a string can be used to store the received data.
A client-server program's fundamental flow is as follows:
- The server program generates a socket to receive incoming connections and binds it to a particular IP address and port.
- Additionally, the client program builds a socket and links it to the IP address and port of the server.
- The client sends a request message to the server through the network using the established connection.
- The request is received by the server, which then processes it and creates a message in response.
- The response message is returned to the client by the server.
- After receiving the response, the client handles it as necessary.
The main actions for setting up a client-server program in C for the client side are as follows:
- Use the socket() system function to create a socket.
- Create the server address structure (for instance, using struct sockaddr_in).
- The connect() system function links the client socket to the server's IP address and port.
- Use the send() system method to send a message of request to the server.
- Use the recv() system function to obtain the server's answer.
- As required, process the response data.
- When the communication is finished, close the client socket.
Server :
In this part, the term "Server" is introduced, and the many server-implemented functions are used to explain the socket workflow. A considerable computer that is fast and has a lot of storage, or both runs applications. A user interaction technique is typically absent from server applications because of the way they are written. It does it by waiting for connections from other programs. A server application typically has access to a lot of data and can access it quickly and effectively. Additionally, it can manage several client requests at once (more or less).
Workflow:
- A socket will first be generated (just as the client program).
- The bind() function will then be used to bind the socket's IP address and port (the server will use the bind() function to listen for connections; the client will use the connect() function to connect to it).
- After that, the listen() method is invoked to monitor connections and determine whether clients are attempting to connect to the server socket.
- It calls the accept() function. The function returns the client socket (the connected client).
The main actions for setting up a client-server program in C for the server side are as follows:
- Use the socket() system function to create a socket.
- Create the server address structure (for instance, using struct sockaddr_in).
- The bind() system function connects the socket to a specific IP address and port.
- Use the listen() system function to begin listening for incoming connections.
- Utilize the accept() system call to accept incoming connections, which makes a new socket for every client.
- Utilize the accepted sockets to handle client requests iteratively.
- Process client requests, reply with your response, and disconnect when finished.
Socket:
A socket is a piece of hardware that facilitates communication between various processes running on the same computer or various systems. A socket enables communication by sending and receiving data through the network. To put it simply, it is a method for a computer to communicate with other computers on the network.
One endpoint of a two-way communication channel between two network-running programs is a socket. A socket is tied to a port number for the TCP layer to recognize the application that data is intended to be transferred.
Transmission Control Protocol:
The Transmission Control Protocol is referred to as TCP. It is one of the most widely used Internet communication protocols. Some characteristics of this protocol include:
- This protocol is used for communication that is connection-oriented.
- A three-way handshake was utilized to create trustable relationships.
- TCP guarantees the delivery of the data packets.
Client-server architecture:
In computer networking, a client-server architecture is a concept where the server offers a service to the client. In this design, a request is sent from the client computer to the server computer via a network (the internet). After agreeing to this request, the server provides the requested information to the client. Simply put, we can state:
- A distant computer that offers some services is the server.
- The client requests these services from the server.
Server-side code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(){
char *ip = "127.0.0.1";
int port = 5566;
int server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_size;
char buffer[1024];
int n;
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock < 0){
perror("[-]Socket error");
exit(1);
}
printf("[+]TCP server socket created.\n");
memset(&server_addr, '\0', sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = port;
server_addr.sin_addr.s_addr = inet_addr(ip);
n = bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (n < 0){
perror("[-]Bind error");
exit(1);
}
printf("[+]Bind to the port number: %d\n", port);
listen(server_sock, 5);
printf("Listening...\n");
while(1){
addr_size = sizeof(client_addr);
client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_size);
printf("[+]Client connected.\n");
bzero(buffer, 1024);
recv(client_sock, buffer, sizeof(buffer), 0);
printf("Client: %s\n", buffer);
bzero(buffer, 1024);
strcpy(buffer, "HI, THIS IS SERVER. HAVE A NICE DAY!!!");
printf("Server: %s\n", buffer);
send(client_sock, buffer, strlen(buffer), 0);
close(client_sock);
printf("[+]Client disconnected.\n\n");
}
return 0;
}
Output:
![Client-server program in C](https://static.tutorialandexample.com/c/client-server-program-in-c1.png)
Client-side code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(){
char *ip = "127.0.0.1";
int port = 5566;
int sock;
struct sockaddr_in addr;
socklen_t addr_size;
char buffer[1024];
int n;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0){
perror("[-]Socket error");
exit(1);
}
printf("[+]TCP server socket created.\n");
memset(&addr, '\0', sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = port;
addr.sin_addr.s_addr = inet_addr(IP);
connect(sock, (struct sockaddr*)&addr, sizeof(addr));
printf("Connected to the server.\n");
bzero(buffer, 1024);
strcpy(buffer, "HELLO, THIS IS CLIENT.");
printf("Client: %s\n", buffer);
send(sock, buffer, strlen(buffer), 0);
bzero(buffer, 1024);
recv(sock, buffer, sizeof(buffer), 0);
printf("Server: %s\n", buffer);
close(sock);
printf("Disconnected from the server.\n");
return 0;
}
Output:
![Client-server program in C](https://static.tutorialandexample.com/c/client-server-program-in-c2.png)
Benefits of Client server program:
Client-server programs are favored for many networked applications because they provide several advantages. Client-server programs have several significant benefits, including:
- Security: Client-server architectures provide a secure environment by allowing for the storage and protection of sensitive data and essential programs on the server. It makes it possible to apply security mechanisms like access restriction, authentication, and encryption more successfully.
- Flexibility and interoperability: As long as client-server applications follow standard communication protocols, they can be created utilizing a variety of client- and server-side technologies. Because of this flexibility, developers can choose the finest tools and languages for each component.
- Lower Bandwidth Usage: Network traffic can be decreased because only necessary data is transferred between the client and server in client-server designs. It may be very useful for situations with constrained bandwidth.
- Client-Side Responsiveness: Client applications can concentrate on delivering a better user experience through responsive user interfaces, as the server handles the majority of the processing and data administration.
- Load balancing: Client-server architectures enable load balancing for high-traffic applications. The workload can be divided among several servers, ensuring effective resource use and avoiding performance bottlenecks.
- Concurrent Access: The server can control access to shared resources concurrently, maintaining data consistency and preventing conflicts when several clients try to use the same resource simultaneously.
- Simplified Upkeep: Client-server systems enable more straightforward upkeep and updates. There is less need for individual updates on each client machine because changes to the server-side components may be disseminated to all clients.
- Scalability: Client-server systems make scaling straightforward. Powerful PCs with higher resources can host servers, assuring improved speed and responsiveness while handling several customers concurrently.
- Centralized Management: Client-server models offer a centralized method of managing data, applications, and resources. Administrators can quickly manage access controls, place security measures, and preserve data integrity due to the server's role as a central repository.
- Resource Sharing: Multiple clients can share resources due to the centralized servers. Clients can access and share common resources like databases, files, or processing power, minimizing duplication and maximizing resource utilization.
In general, client-server programs offer a structured and effective method of managing distributed computing task. It makes them appropriate for various applications, from web servers and cloud-based services to database management systems and online gaming platforms.