Creating your own chat server with C

Shreeya Chatterji
Google Developer Student Clubs TIET
5 min readOct 14, 2023

From Facebook to Instagram to WhatsApp every major hit🎯 application includes a chatting feature💬. Chatting is specially an important part for games. In this article I will go through the code to create a chat server using TCP socket programming👩‍💻.

Source- Wallpaper Access

To create a chat server we must first understand what it actually is. A chat server is a software application that enables real-time communication between users over a network, typically the internet. It’s a server instance that provides resources for a chat service. The server accepts messages sent by the user of a chat client and forwards them to the recipient(s).

What is TCP?

Transmission Control Protocol (TCP) is a standard that defines how to establish and maintain a network conversation by which applications can exchange data.

TCP works with the Internet Protocol (IP), which defines how computers send packets of data to each other. Together, TCP and IP are the basic rules that define the internet. The Internet Engineering Task Force (IETF) defines TCP in the Request for Comment (RFC) standards document number 793.

In the Open Systems Interconnection (OSI) communication model, TCP covers parts of Layer 4, the transport layer, and parts of Layer 5, the session layer.

When a web server sends an HTML file to a client, it uses the hypertext transfer protocol (HTTP) to do so. The HTTP program layer asks the TCP layer to set up the connection and send the file. The TCP stack divides the file into data packets, numbers them and then forwards them individually to the IP layer for delivery.

Thus, creating a simple TCP chat server can be your beginning to creating online web chat server.

Why TCP?

TCP guarantees the integrity of data sent over the network, regardless of the amount. For this reason, it is used to transmit data from other higher-level protocols that require all transmitted data to arrive.

Some other protocols and their functions include the following:

  • Secure Shell (SSH), File Transfer Protocol (FTP), Telnet: For peer-to-peer file sharing, and, in Telnet’s case, logging into another user’s computer to access a file.
  • Simple Mail Transfer Protocol (SMTP), Post Office Protocol (POP), Internet Message Access Protocol (IMAP): For sending and receiving email.
  • HTTP: For web access.

These examples all exist at the application layer of the TCP/IP stack and send data downwards to TCP on the transport layer.

Who is the Client?

The client is basically the party that requests some services from the server. Without the server the client is basically not functional.

In a client-server model, a client is a user or machine that requests services from a server. For example, a web browser like Google Chrome or Firefox is a client.

The client initiates a connection request to the server. The client’s job is to:

  • Connect to the server
  • Send a message to the server
  • Receive a response from the server
  • Terminate the connection

Who is the Server?

A TCP server is an application that listens for TCP connections from TCP clients. The server can be run on the same machine as the client or on a different machine.

The server’s job is to:

  • Listen on a well-known port or IP address and port pair
  • Accept connections from TCP clients
  • Organize data so that it can be transmitted between the server and the client
  • Guarantee the integrity of the data being communicated over a network
  • Ensure the connection remains live until communication begins

How to get started?

First we must jot down the steps to creating a chat server in TCP. So that we can better understand how the communication will take place between the client and server.

Flowchart to understand the communication process (Source: GFG)

The flowchart above describes the main functions in the Client and Server required to build the connection and begin the chatting between the client and server.

Understanding the process for the code:

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.

Now let’s code!

NOTE✨: It is suggested you do this on a Linux Operating system. If you do not have a Linux Based OS you may try doing it on an online virtual machine or on any virtual machine on your desktop.

SERVER

#include<sys/types.h> //including data types
#include<sys/socket.h> //listening
#include<netdb.h> //provide network db operations
#include<fcntl.h> //open the connection
#include<unistd.h> //close the connection
#include<stdio.h>
#include<string.h>

int main()
{
char str[100]; //receiving data
char sendline1[100];
bzero(sendline1,100);
int listen_fd,comm_fd;
struct sockaddr_in servaddr; //IPv4_IPv6, IP add, PORT add

//creating a socket, address family inet(using v4),use INET6 for v6
listen_fd=socket(AF_INET,SOCK_STREAM,0);
//SOCK_STREAM = TCP, SOCK_DGRAM = UDP
//0 is default protocol not flag operation


bzero(str,100); //want to make 100 bytes 0
bzero(&servaddr,sizeof(servaddr)); //initialize all values with 0

//defining server address..passing those 3 parameters
servaddr.sin_family=AF_INET; //IPv4
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
//server will connect with any IP addr
//htonl is used to convert host byte into network byte
servaddr.sin_port=htons(21000);
//0 to 65,535....first 1024 ports are fixed


//binding server addr with socket
bind(listen_fd,(struct sockaddr *)&servaddr,sizeof(servaddr));

//listening
listen(listen_fd,5); //5 clients can be connected to the server

//to establish connection with client...like a pipeline
comm_fd=accept(listen_fd,(struct sockaddr *)NULL,NULL);

//client initializing data
while(1){
recv(comm_fd,str,100,0); //hardcoded 100 because we do not know length of incoming stream
printf("Client: %s",str);
printf("Your message: ");
fgets(sendline1,100,stdin);
send(comm_fd,sendline1,strlen(sendline1),0);
bzero(sendline1,100);
//0 is flag operation...tells abt successfull and unsuccessfull op
}
close(comm_fd);
}

CLIENT

#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<string.h>


int main()
{
int sockfd;
char sendline[100];
char recvline[100];
struct sockaddr_in servaddr;
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(sendline,100);
bzero(recvline,100);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(21000);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

while(1){
printf("Your Message: ");
fgets(sendline,100,stdin);
send(sockfd,sendline,strlen(sendline),0);
recv(sockfd,recvline,100,0);
printf("Server : %s",recvline);
}

}

The descriptions for the important functions is provided in the first code which will help you understand the functions and map out the flowchart to the code.

How to run the codes?

First we compile the codes.

gcc server.c -o server
gcc client.c -o client

Then run the server.

./server

In a different terminal run the client.

./client

Now in the client terminal you may begin the chatting. And reply in the server terminal. This is how your outputs will look.

The server terminal
The client terminal

Congratulations! You have built your very own chat server!✨🥳

EXERCISE: Now you may try adding a break condition so that the application stops on entering a codeword like “exit”.

I have tried to be as accurate as possible. Feel free to drop any suggestions or doubts in the comments section below.

“Hustle on and Keep Learning! Peace ☮️”

--

--