Skip to main content

TCP Socket Programming in Unix Using C Programming

1 min read
Share:
On this page (3sections)

TCP Socket Programming in Unix Using C Programming

Server

Client

Introduction to TCP Socket Programming in Unix using C Programming

TCP (Transmission Control Protocol) is a widely used transport layer protocol in networking that provides reliable, ordered, and error-checked delivery of data between applications. Socket programming allows communication between processes on different or the same devices over a network using TCP/IP protocols. In this blog post, we will explore how to implement a simple ECHO CLIENT-SERVER communication using TCP sockets in C programming language on a Unix-based system.

Concept of TCP Socket Programming

Socket Programming is a powerful paradigm for network communication, and TCP sockets offer a reliable, stream-oriented, connection-based communication channel. The TCP server listens for incoming connections, and when a client connects, a new socket is created for that client, allowing data exchange between the client and the server. The TCP client establishes a connection with the server and can send and receive data through the established connection.

ECHO Server Implementation

Let’s start by explaining the server implementation:

#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <fcntl.h>
int main() {
    int sd, cd;

    char buf[100] = "";

    struct sockaddr_in ser;

    // Create the socket

    sd = socket(AF_INET, SOCK_STREAM, 0);

    if (sd < 0) {

        printf(“SOCKET NOT CREATED\n”);

        return 1;

    }

    // Bind the socket to an IP and Port

    bzero(&ser, sizeof(struct sockaddr_in));

    ser.sin_family = AF_INET;

    ser.sin_port = htons(1012);

    inet_aton(“172.16.29.78”, &ser.sin_addr);

    int b = bind(sd, (struct sockaddr*)&ser, sizeof(ser));

    printf(“BIND VALUE: %d\n”, b);

    // Start listening for incoming connections

    listen(sd, 5);

    for (;;) {

        //

Related Tutorials

Search tutorials