Complete Communications Engineering

One way to do this is using a makefile project with the C programming language on Linux.  A TCP client is a program that connects to a TCP server, so the client initiates the connection and the server receives connection requests.  In order to initiate a connection, the client needs to know the address and port of the server it will connect to.  This information may be known ahead of time, or the DNS protocol might be used to look it up from a given domain name.  Once the address is known, the client can create a TCP socket and try to connect.  If the connection succeeds, data can be written to and read from the server.

The following C code implements a simple TCP client:

client.c

#include <stdio.h>

#include <string.h>

#include <unistd.h>

#include <sys/socket.h>

#include <netinet/ip.h>

#include <arpa/inet.h>

 

int main (int argc, char *argv[])

{

    int s, len, result;

    struct sockaddr_in srv_addr;

    char buf[64];

 

    /* Address and port of the server to connect to */

    srv_addr.sin_family = AF_INET;

    srv_addr.sin_port = 9001;

    inet_pton(AF_INET, “127.0.0.1”, &srv_addr.sin_addr);

 

    /* Create a socket and try to connect */

    s = socket(AF_INET, SOCK_STREAM, 0);

    result = connect(s, (struct sockaddr *)&srv_addr, sizeof(srv_addr));

 

    /* Exchange some data if the connection succeeded */

    if (result == 0) {

        sprintf(buf, “Hello from the client”);

        write(s, buf, strlen(buf) + 1);

        len = read(s, buf, sizeof(buf));

        printf(“Received message from server: ‘%s’\n”, buf);

    }

 

    /* Done */

    close(s);

    return 0;

}

The example code first sets the IP address and port of the server it will try to connect to.  After that it creates a TCP socket and attempts to establish a TCP connection to the server.  The ‘connect’ function will return 0 if the connection was established successfully.  In this case, the program writes a simple message to the server and reads a response.  After the messages are exchanged, the socket is closed and the program exits.