TCP/IP Socket Programming in C and C++ (Client Server Program)

This tutorial will help you to know about concept of TCP/IP Socket Programming in C and C++ along with client server program example.

What is Socket?

We know that in Computer Networks, communication between server and client using TCP/IP protocol is connection oriented (which buffers and bandwidth are reserved for client). Server will get so many hits from different clients, and then server has to identify each client uniquely to reply every request. To achieve this we use “ip address of client (32 bit) + port number (16 bit) of the process”. This is called Socket (48 bit). Any network communication should goes through socket.

Procedure in Client-Server Communication

  • Socket: Create a new communication
  • Bind: Attach a local address to a socket
  • Listen: Announce willingness to accept connections
  • Accept: Block caller until a connection request arrives
  • Connect: Actively attempt to establish a connection
  • Send: Send some data over connection
  • Receive: Receive some data over connection
  • Close: Release the connection

TCP IP Socket Programming (Client and Server)

Image Source

Client Server Program Using Socket Programming in C and C++

Let’s see how to create server and client using C programming. Below code will work in C++ also.

We now create a server which run continuously, and if any client hit the server with a request then server will send it’s date and time. To know the success message we here printing that time and date.

server.c

#include <stdio.h> // standard input and output library
#include <stdlib.h> // this includes functions regarding memory allocation
#include <string.h> // contains string functions
#include <errno.h> //It defines macros for reporting and retrieving error conditions through error codes
#include <time.h> //contains various functions for manipulating date and time
#include <unistd.h> //contains various constants
#include <sys/types.h> //contains a number of basic derived types that should be used whenever appropriate
#include <arpa/inet.h> // defines in_addr structure
#include <sys/socket.h> // for socket creation
#include <netinet/in.h> //contains constants and structures needed for internet domain addresses

int main()
{
    time_t clock;
	char dataSending[1025]; // Actually this is called packet in Network Communication, which contain data and send through.
	int clintListn = 0, clintConnt = 0;
	struct sockaddr_in ipOfServer;
	clintListn = socket(AF_INET, SOCK_STREAM, 0); // creating socket
	memset(&ipOfServer, '0', sizeof(ipOfServer));
	memset(dataSending, '0', sizeof(dataSending));
	ipOfServer.sin_family = AF_INET;
	ipOfServer.sin_addr.s_addr = htonl(INADDR_ANY);
	ipOfServer.sin_port = htons(2017); 		// this is the port number of running server
	bind(clintListn, (struct sockaddr*)&ipOfServer , sizeof(ipOfServer));
	listen(clintListn , 20);

	while(1)
	{
		printf("\n\nHi,Iam running server.Some Client hit me\n"); // whenever a request from client came. It will be processed here.
		clintConnt = accept(clintListn, (struct sockaddr*)NULL, NULL);

		clock = time(NULL);
		snprintf(dataSending, sizeof(dataSending), "%.24s\r\n", ctime(&clock)); // Printing successful message
		write(clintConnt, dataSending, strlen(dataSending));

        close(clintConnt);
        sleep(1);
     }

     return 0;
}

Explanation

1. socket() function creates a new socket inside kernel and returns an integer which used as socket descriptor.

2. For IP4 address we are sending first argument as AF_INET. You can also see we are assigning ipOfServer = AF_INET, represents that this argument related to Internet IP addresses.

3. SOCK_STREAM argument confirms that we are using TCP as a protocol in this communication, which is reliable communication.

4. Sending ‘0’ as third argument is, we are saying to kernel that use default protocol

5. Next we have to bind the created socket to structure ipOfServer. For this we are calling bind() functional. Which includes port, ip addresses as details.

6. listen() also an inbuilt function the 2nd argument 20 says that maximum 20 number of clients can connect to that server. So maximum 20 queue process can be handled by server.

7. Upto now server started. Next server waits for client request by accept() function.

8. accept() runs infinite loop to keep server always running. But it may eat up all CPU processing, to avoid that we have written sleep(1), which server went to sleep for 1 sec.

9. When server hit by client, it prints date and time on clients socket through descriptor returned by accept().

client.c

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>

int main()
{
    int CreateSocket = 0,n = 0;
    char dataReceived[1024];
    struct sockaddr_in ipOfServer;

    memset(dataReceived, '0' ,sizeof(dataReceived));

    if((CreateSocket = socket(AF_INET, SOCK_STREAM, 0))< 0)
    {
        printf("Socket not created \n");
        return 1;
    }

    ipOfServer.sin_family = AF_INET;
    ipOfServer.sin_port = htons(2017);
    ipOfServer.sin_addr.s_addr = inet_addr("127.0.0.1");

    if(connect(CreateSocket, (struct sockaddr *)&ipOfServer, sizeof(ipOfServer))<0)
    {
        printf("Connection failed due to port and ip problems\n");
        return 1;
    }

    while((n = read(CreateSocket, dataReceived, sizeof(dataReceived)-1)) > 0)
    {
        dataReceived[n] = 0;
        if(fputs(dataReceived, stdout) == EOF)
        {
            printf("\nStandard output error");
        }

        printf("\n");
    }

    if( n < 0)
    {
        printf("Standard input error \n");
    }

    return 0;
}

Explanation

This code can connect to server and receive date and time from server.

1. Since this communication through socket, here also, we created socket.

2. Port number of the process and IP address both bundled in a structure. We connect these with socket

3. Once sockets are connected, the server sends the date and time to client socket through clients socket descriptor.

How to run server.c and client.c files?

First run server.c file and create an output file for that in Unix or Linux.

Type gcc server.c -o server command in terminal.

Now run the server using ./server

Socket Programming in C 1

After running the server just minimize the terminal. Open new terminal. Do remaining work there.

To know the server is running or not we can check using netstat command.

After opening new terminal, type sudo netstat -ntlp

Here we can see running server with port 2017

Socket Programming in C 2

Now check with client by sending request with same port:

Type gcc client -o client

Type ./client

After that you can see the date and time which is sent by server.

Socket Programming in C 3

It means connection established successfully.

Whenever we run client program that means we are requesting the server, every time server will send date and time saying that connection established successfully.

Comment below if you have queries or found something incorrect in above tutorial for socket programming in C and C++.

13 thoughts on “TCP/IP Socket Programming in C and C++ (Client Server Program)”

  1. Sir I would like to thank you for all the codes that helped me in my assesments.
    Without you I was in Dark.
    Thanks for showing me the way.
    If ever i get a chance to meet you my life would be complete.

    1. setsockopt is optional. It helps in reducing errors such as “Address already in use” and helps is reuse of address and port. It helps in manipulating options for the socket referred by the file descriptor.

  2. Really cool, it actually works unlike other tutorials. Now I want to know how to make a simple chat program using tcp/ip and a native Linux app.

  3. How do I make it so when the server restarts, the client is able to connect in the same session, without having to restart the client?

Leave a Comment

Your email address will not be published. Required fields are marked *