The Wayback Machine - https://web.archive.org/web/20241011025616/https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/
Open In App

TCP Server-Client implementation in C

Last Updated : 18 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites – Socket Programming in C/C++, TCP and UDP server using select, UDP Server-Client implementation in C 

If we are creating a connection between client and server using TCP then it has a few functionalities like, TCP is suited for applications that require high reliability, and transmission time is relatively less critical. It is used by other protocols like HTTP, HTTPs, FTP, SMTP, Telnet. TCP rearranges data packets in the order specified. There is absolute guarantee that the data transferred remains intact and arrives in the same order in which it was sent. TCP does Flow Control and requires three packets to set up a socket connection before any user data can be sent. TCP handles reliability and congestion control. It also does error checking and error recovery. Erroneous packets are retransmitted from the source to the destination.

The entire process can be broken down into the following steps:
 

The entire process can be broken down into following steps:

TCP Server – 

  1. using create(), Create TCP socket.
  2. using bind(), Bind the socket to server address.
  3. using listen(), put the server socket in a passive mode, where it waits for the client to approach the server to make a connection
  4. using accept(), At this point, connection is established between client and server, and they are ready to transfer data.
  5. Go back to Step 3.

TCP Client – 

  1. Create TCP socket.
  2. connect newly created client socket to server.

TCP Server:

C




#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
   
// Function designed for chat between client and server.
void func(int connfd)
{
    char buff[MAX];
    int n;
    // infinite loop for chat
    for (;;) {
        bzero(buff, MAX);
   
        // read the message from client and copy it in buffer
        read(connfd, buff, sizeof(buff));
        // print buffer which contains the client contents
        printf("From client: %s\t To client : ", buff);
        bzero(buff, MAX);
        n = 0;
        // copy server message in the buffer
        while ((buff[n++] = getchar()) != '\n')
            ;
   
        // and send that buffer to client
        write(connfd, buff, sizeof(buff));
   
        // if msg contains "Exit" then server exit and chat ended.
        if (strncmp("exit", buff, 4) == 0) {
            printf("Server Exit...\n");
            break;
        }
    }
}
   
// Driver function
int main()
{
    int sockfd, connfd, len;
    struct sockaddr_in servaddr, cli;
   
    // socket create and verification
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }
    else
        printf("Socket successfully created..\n");
    bzero(&servaddr;, sizeof(servaddr));
   
    // assign IP, PORT
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(PORT);
   
    // Binding newly created socket to given IP and verification
    if ((bind(sockfd, (SA*)&servaddr;, sizeof(servaddr))) != 0) {
        printf("socket bind failed...\n");
        exit(0);
    }
    else
        printf("Socket successfully binded..\n");
   
    // Now server is ready to listen and verification
    if ((listen(sockfd, 5)) != 0) {
        printf("Listen failed...\n");
        exit(0);
    }
    else
        printf("Server listening..\n");
    len = sizeof(cli);
   
    // Accept the data packet from client and verification
    connfd = accept(sockfd, (SA*)&cli;, &len;);
    if (connfd < 0) {
        printf("server accept failed...\n");
        exit(0);
    }
    else
        printf("server accept the client...\n");
   
    // Function for chatting between client and server
    func(connfd);
   
    // After chatting close the socket
    close(sockfd);
}


TCP Client:

C




#include <arpa/inet.h> // inet_addr()
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
    char buff[MAX];
    int n;
    for (;;) {
        bzero(buff, sizeof(buff));
        printf("Enter the string : ");
        n = 0;
        while ((buff[n++] = getchar()) != '\n')
            ;
        write(sockfd, buff, sizeof(buff));
        bzero(buff, sizeof(buff));
        read(sockfd, buff, sizeof(buff));
        printf("From Server : %s", buff);
        if ((strncmp(buff, "exit", 4)) == 0) {
            printf("Client Exit...\n");
            break;
        }
    }
}
 
int main()
{
    int sockfd, connfd;
    struct sockaddr_in servaddr, cli;
 
    // socket create and verification
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }
    else
        printf("Socket successfully created..\n");
    bzero(&servaddr;, sizeof(servaddr));
 
    // assign IP, PORT
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(PORT);
 
    // connect the client socket to server socket
    if (connect(sockfd, (SA*)&servaddr;, sizeof(servaddr))
        != 0) {
        printf("connection with the server failed...\n");
        exit(0);
    }
    else
        printf("connected to the server..\n");
 
    // function for chat
    func(sockfd);
 
    // close the socket
    close(sockfd);
}


Compilation – 
Server side: 
gcc server.c -o server 
./server

Client side: 
gcc client.c -o client 
./client

Output – 

Server side: 

Socket successfully created..
Socket successfully binded..
Server listening..
server accept the client...
From client: hi
     To client : hello
From client: exit
     To client : exit
Server Exit... 

Client side: 

Socket successfully created..
connected to the server..
Enter the string : hi
From Server : hello
Enter the string : exit
From Server : exit
Client Exit... 


Similar Reads

TCP with explicit link failure notification (TCP-ELFN)
TCP with Explicit Link Failure Notification (TCP-ELFN) is an end to end approach used in TCP Ad Hoc wireless networks to improve the performance by decoupling the path break information from congestion information. TCP-ELFN does not depend upon any routing protocols as it requires explicitly only the link failure notification when there is a path f
2 min read
TCP Tahoe and TCP Reno
TCP is known as a connection-oriented protocol, which ensures reliability and is also responsible for congestion control mechanisms in the network. TCP Tahoe and TCP Reno are two techniques of TCP congestion control, these are used when the sender receives three duplicate acknowledgments. TCP Tahoe where Tahoe is a lake in the USA. This particular
4 min read
TCP Fast Open and TCP/IP Acceleration
The TCP Fast Open (TFO) and TCP/IP Acceleration are techniques used to improve the performance and efficiency of TCP connections in computer networks. These techniques aim to reduce the latency and improve the throughput of the TCP connections, especially for short-lived connections and web browsing scenarios. TCP Fast Open (TFO): The TCP Fast Open
3 min read
Setting up local DNS server between client-server machines
In this, article you will see the overview of DNS server and how to set up the local DNS server between the client and server machines. And here we will use Wireshark. Let's discuss it one by one. Introduction :A DNS server is computer server that contains a database of public IP addresses and their associated hostname, and in most cases serves to
5 min read
Reverse a string in C/C++ using Client Server model
This article describes a Client and Server setup where a Client connects, sends a string to server and the server shows the original string and sends reversed string to client using socket connection. Prerequisite : Socket Programming Examples: Input : welcome Output :emoclew Input :geeks for geeks Output :skeeg rof skeeg Explanation In this, first
3 min read
Distributed Objects Computing: The next generation of client-server computing
Software technology is in the midst of a major computational shift towards distributed object computing DOC. Distributed computing is poised for a second client-server revolution, a transition from first generation client-server era to the next generation client-server era. In this new client-server model, servers are plentiful instead of scarce(be
2 min read
Simple client/server application in C
Overview :Create a simple client/server application in C using the concept of socket programming. Where server send some message to the client when getting connected. Client : In this section, the term ‘Client’ is defined and its socket workflow is explained in detail, through different functions used to implement the client. An application that ru
4 min read
What are the Two Broad Classes of Middleware in Client Server Environment?
Server: A server is a computer program that provides services, data, information to other computer programs. Client: A client is a host computer, requests services or information from the server. the client is also called a user. In a computer system, a client is a computer program that asks something from the server and the server gives the inform
5 min read
Difference Between Server OS and Client OS
Client Operating Systems and Server Operating Systems are two awesome sorts of operating systems designed to serve exclusive purposes inside a computer network surroundings. While each form of working system shares some similarities in phrases of basic functionalities, they're optimized for different use instances and feature particular functions t
7 min read
Difference between Client-Server and Peer-to-Peer Network
In the world of network architecture, two fundamental models are widely utilized to structure data exchange and resource sharing. For the purpose of this discussion, two types of networks are available; the Client-Server Network and the Peer-to-Peer Network. All the models have their strengths, weaknesses, and appropriate applications that make the
4 min read
Difference between Client side filter and Server side filters in Cyber Security
Filters are key components in web applications that validate user input and ensure it meets certain standards. These filters can be implemented on the client side (within the user's web browser) or the server side (on the web server). Understanding the differences between client-side and server-side filters is necessary to maintain data quality and
5 min read
Difference Between Client /Server and Distributed DBMS
In today's digital era, managing large volumes of data efficiently and effectively is very crucial for any organization. Here we have the requirement of a Database and to manage it we also require a management system. Two most popular database management systems are Client/Server DBMS and Distributed DBMS. Both aim to facilitate data storage, data
7 min read
How to Boost Linux Server Internet Speed with TCP BBR?
BBR is a modern TCP congestion control algorithm. It was put to the test in Google's data center networks and on some of their public-facing Web servers, such as Google.com and YouTube. By estimating the bottleneck bandwidth and RTT to calculate a pacing rate, it aims to optimize both throughput and latency/RTT. One target, which distinguishes it f
2 min read
What Is Client Side Exploitation
Introduction:-Nowadays Server side is getting strong day by day but there are still vulnerabilities present on the client-side and this leads to client-side exploitation. This article will introduce you to various client-side exploitation techniques that can be used in a penetration test. Client-side exploits are very useful to attackers when the c
5 min read
How to Connect to Amazon Linux Instance from Windows Client Operating System using PUTTY?
In this article, we will learn how to connect the Amazon Linux instances from Windows client operating system. For this we will be performing the following operations: Create a Linux instance in Amazon AWS.Using putty application connect to the Linux instance from the windows client operating system.Create a Linux instance in Amazon AWS: Follow the
2 min read
What is an email client?
Electronic mail (email) can be defined as a process of exchanging information/messages stored in a computer system by using an internet communication system. Emails generally contain text but nowadays media and other types of files can also be attached. When an email is sent then it goes to a remote computer say email server and stored there until
5 min read
How to configure SSH Client in Linux ?
At times we may need to access multiple remote systems with different IP addresses/hostnames, usernames, non-standard-ports with various command-line options. One way is to create a bash alias for each remote connection. But we have an easy and much better solution to this problem. OpenSSH allows to create per-user configuration file to store diffe
4 min read
How to Install Latest ‘Thunderbird’ Email Client in Linux
Thunderbird is a free open-source web-based email, news, and chat client application that can manage numerous email accounts and news feeds. How to install Thunderbird in Linux Step 1: Run the command below on a Kali Linux machine to install this software. sudo apt-get update Step 2: After you've updated the system, run the following command to ins
1 min read
How to Install SQL Client in Linux?
In this article, we will discuss how to install the MySQL client in Debian OS. Step to Install MySQL client Step 1: Run the below command to Update Linux packages. sudo apt-get update -y Step 2: Run the below commands to install the packages required to install MySQL Client. sudo apt-get install wget -ysudo apt install gnupg -y Step 3 Run the below
1 min read
How to Prevent a Background Process From Being Stopped after Closing SSH client in Linux
What is Background Process? A Background Process is an ongoing process running independently, and that is not visible to the users as it runs without any user interaction after the terminal has been closed. Some of the well-known examples of Background processes are the web servers like Nginx and Apache. The Nginx discovers the file and sends it to
4 min read
How to Identify a HTTP Request is Sent by a Local Network Computer or by an Internet Client?
Answer: If it falls within private IP ranges e.g., 10.x.x.x, 172.16.x.x to 172.31.x.x, 192.168.x.x, it's from a local network, otherwise, it's from an internet client.Capture the Client's IP Address When your server receives an HTTP request, it typically includes the client's IP address in the request headers or the server's access logs. Analyze th
1 min read
How To Install bacula-client on Ubuntu?
Whatever the Operating System you are using, you should have to take care of your Files on Local Machine. So, you have to rely on the Data Backup & Recovery Feature. The Bacula-Client Application is one best to note. To Install Bacula-Client on Ubuntu Operating System, you will get a series of methods. In this article, we will learn about the B
4 min read
How to Install Deluge BitTorrent Client on Ubuntu?
If you want to get a Powerful & Flexible Torrenting Solution on the Ubuntu Operating System that works on the BitTorrent Client, then the Installation of the Deluge BitTorrent Client will be necessary. The Deluge BitTorrent Client on Ubuntu will help to Download & Upload Files with the BitTorrent Network. In this article, we will discuss th
3 min read
How to Install the Netflix Streaming Client on Linux
Linux has its own challenges regarding Netflix streaming due to the compatibility of certain software. But of course, it is possible. The Linux-supported web official browsers including Google Chrome or Firefox work well with Netflix streaming technology. Therefore, in this guide, you will learn how to stream Netflix using both browsers to get your
3 min read
Basic concept of TCP-Vegas
TCP Reno and TCP Tahoe models can determine the congestion in the network only when there some packet loss occurred in the system. So in these models, we have compensated for the packet to sense the congestion in the network. In these models when packet loss occurs the window size is decreased and the system enters the congestion avoidance phase. W
3 min read
TCP flags
In TCP connection, flags are used to indicate a particular state of connection or to provide some additional useful information like troubleshooting purposes or to handle a control of a particular connection. Most commonly used flags are "SYN", "ACK" and "FIN". Each flag corresponds to 1 bit information. Types of Flags: Synchronization (SYN) - It i
4 min read
What is TCP Window Scaling?
In the TCP header, the window size field is of size 16 bits. Using this field TCP users (client or server) can advertise a maximum of 216 = 65536 bytes or 64 KiB as its buffer size to its other end-user. But modern endpoint devices (e.g., phones, tabs, PCs, etc) have much more memory available in their buffers. This 16-bit field was enough during t
5 min read
Wrap Around Concept and TCP Sequence Number
Prerequisite - TCP | Services and Segment structure Transmission Control Protocol (TCP) is one of the most important protocols of the internet protocol. It provides full transport-layer service to applications and generates a virtual circuit between sender and receiver that is active for the duration of the transmission. Its segment consists of a T
6 min read
Devices used in each layer of TCP/IP model
Prerequisite - TCP/IP Model, Network Devices 1. Physical Layer - Physical layer of TCP/IP model is responsible for physical connectivity of two devices. Some of the devices used in Physical layers are, Hubs: Hubs are devices commonly used to connect segments of a LAN. It contains multiple input/output ports. when signal is at any input port, this s
4 min read
TCP and UDP in Transport Layer
Layer 3 or the Network layer uses IP or Internet Protocol which being a connection less protocol treats every packet individually and separately leading to lack of reliability during a transmission. For example, when data is sent from one host to another, each packet may take a different path even if it belongs to the same session. This means the p
4 min read