Implementation of TCP Client-Server Communication using Sockets

 

Experiment 

Implementation of TCP Client-Server Communication using Sockets


Aim

To implement a simple TCP client-server program using sockets and demonstrate communication between them.


Objective

  • To understand the concept of socket programming
  • To learn how TCP ensures reliable communication
  • To establish communication between client and server processes

Theory

What is a Socket?

A socket is an endpoint for communication between two machines over a network. It allows processes to send and receive data.

What is TCP?

Transmission Control Protocol (TCP) is a connection-oriented protocol that:

  • Ensures reliable data transfer
  • Guarantees data delivery in order
  • Performs error checking and retransmission

Client-Server Model

  • Server waits for incoming requests
  • Client initiates communication
  • Communication happens via:
    • IP Address
    • Port Number

Working of TCP Communication

  1. Server creates a socket
  2. Server binds it to an IP and port
  3. Server listens for connections
  4. Client creates a socket and connects to server
  5. Data exchange happens
  6. Connection is closed

Algorithm

Server Side

  1. Create socket
  2. Bind socket to IP and port
  3. Listen for connections
  4. Accept client connection
  5. Receive message from client
  6. Send response
  7. Close connection

Client Side

  1. Create socket
  2. Connect to server
  3. Send message
  4. Receive response
  5. Close connection

Socket Programming in C

Socket programming provides an interface to communicate between processes over a network using system calls.

Key Functions Used

  • socket() → Create a socket
  • bind() → Assign IP and port
  • listen() → Wait for connections
  • accept() → Accept client request
  • connect() → Client connects to server
  • send() / recv() → Data communication
  • close() → Close socket

TCP Characteristics

  • Connection-oriented
  • Reliable and ordered delivery
  • Error detection and retransmission

Program


๐Ÿ”น Server Program (C)

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #define PORT 12345 int main() { int server_fd, new_socket; struct sockaddr_in address; int addrlen = sizeof(address); char buffer[1024] = {0}; char *message = "Hello from server"; // Create socket server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd == 0) { perror("Socket failed"); exit(EXIT_FAILURE); } // Define address address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Bind if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("Bind failed"); exit(EXIT_FAILURE); } // Listen if (listen(server_fd, 3) < 0) { perror("Listen"); exit(EXIT_FAILURE); } printf("Server is listening...\n"); // Accept connection new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen); if (new_socket < 0) { perror("Accept"); exit(EXIT_FAILURE); } // Read data read(new_socket, buffer, 1024); printf("Client: %s\n", buffer); // Send response send(new_socket, message, strlen(message), 0); printf("Message sent to client\n"); close(new_socket); close(server_fd); return 0; }

๐Ÿ”น Client Program (C)

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #define PORT 12345 int main() { int sock = 0; struct sockaddr_in serv_addr; char *message = "Hello from client"; char buffer[1024] = {0}; // Create socket sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { printf("\nSocket creation error\n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT);     serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); 
    /* Convert IP address different Code - NOT USED HERE if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { printf("\nInvalid address\n"); return -1; } */ // Connect to server if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed\n"); return -1; } // Send message send(sock, message, strlen(message), 0); printf("Message sent to server\n"); // Read response read(sock, buffer, 1024); printf("Server: %s\n", buffer); close(sock); return 0; }

Compilation and Execution

Compile

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

Run

Open two terminals:

Terminal 1 (Server):

./server

Terminal 2 (Client):

./client

Sample Output

Server

Server is listening... Client: Hello from client Message sent to client

Client

Message sent to server Server: Hello from server

Result

The TCP client-server communication was successfully implemented in C, and reliable data transfer was achieved.


๐Ÿ–ฅ️ Server Code Explanation (Step by Step)

int server_fd, new_socket;
  • server_fd: Socket descriptor for the server
  • new_socket: Used for communication with the client

struct sockaddr_in address;
  • Structure to store:
    • IP address
    • Port number
    • Address family
struct sockaddr_in {
    short int sin_family;
    unsigned short int sin_port;
    struct in_addr sin_addr;
};
  • sin_familySocket Internet Family
  • sin_portSocket Internet Port
  • sin_addrSocket Internet Address

int addrlen = sizeof(address); char buffer[1024] = {0}; char *message = "Hello from server";
  • addrlen: Size of address structure
  • buffer: To store incoming data
  • message: Response to client

๐Ÿ”น Step 1: Create Socket

server_fd = socket(AF_INET, SOCK_STREAM, 0);
  • AF_INET → IPv4
  • SOCK_STREAM → TCP
  • Returns a socket descriptor

๐Ÿ”น Step 2: Configure Address

address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT);
  • AF_INET → IPv4  ( AF_INET6 → IPv6 )
  • INADDR_ANY → Accept connections from any IP
  • htons(PORT) → Convert port to network byte order ( htons = Host TO Network Short )

๐Ÿ”น Step 3: Bind Socket

bind(server_fd, (struct sockaddr *)&address, sizeof(address));
  • Links socket to:
    • IP address
    • Port number
  • Makes server reachable

๐Ÿ”น Step 4: Listen for Connections

listen(server_fd, 3);
  • Server starts listening
  • 3 → Maximum pending connections (queue size)

๐Ÿ”น Step 5: Accept Client

new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
  • Accepts incoming connection
  • Returns a new socket for communication
  • Original socket continues listening

๐Ÿ”น Step 6: Receive Data

read(new_socket, buffer, 1024);
  • Reads message sent by client
  • Stores in buffer

๐Ÿ”น Step 7: Send Response

send(new_socket, message, strlen(message), 0);
  • Sends data back to client

๐Ÿ”น Step 8: Close Connections

close(new_socket); close(server_fd);
  • Closes:
    • Client connection
    • Server socket

๐ŸŒ Client Code Explanation (Step by Step)

int sock = 0; struct sockaddr_in serv_addr;
  • sock: Client socket descriptor
  • serv_addr: Server address info

char *message = "Hello from client"; char buffer[1024] = {0};
  • Message to send
  • Buffer to receive response

๐Ÿ”น Step 1: Create Socket

sock = socket(AF_INET, SOCK_STREAM, 0);
  • Same as server:
    • IPv4 + TCP

๐Ÿ”น Step 2: Set Server Details

serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  • Define server:
    • Address family
    • Port
    • Converts IP string → binary format required by the system
    • "127.0.0.1" means:
      • Loopback address (localhost)
      • Refers to same machine

๐Ÿ”น Step 3: Convert IP Address ( optional not used here)

inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
  • Converts IP string → binary format
  • "127.0.0.1" → localhost

๐Ÿ”น Step 4: Connect to Server

connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
  • Initiates TCP connection
  • Performs 3-way handshake

๐Ÿ”น Step 5: Send Data

send(sock, message, strlen(message), 0);
  • Sends message to server

๐Ÿ”น Step 6: Receive Response

read(sock, buffer, 1024);
  • Receives reply from server

๐Ÿ”น Step 7: Close Socket

close(sock);

  • Terminates connection

Comments

Popular posts from this blog

Networks Lab PCCSL507 Semester 5 KTU CS 2024 Scheme - Dr Binu V P

Analysis of HTTP Protocol using Wireshark

Study and Use of ifconfig Command