Complete Communications Engineering

One way to do this is using a makefile project with the C programming language on Linux.  The Berkeley sockets API is supported natively in Linux.  It’s also supported on Windows, but is a little more complicated to setup on that platform.  A TCP server program will first create a TCP socket and bind it to a local address and port.  It will then listen for incoming client connections on that socket.  When a client connection is received, a new socket is created for the connection.  The new socket is used to read data from and write data to the client.  Most TCP servers can handle multiple connections at one time by continuing to listen on the original socket while active connections are handled in parallel.  To keep this example simple, only a single connection is supported.

The following C code implements a simple TCP server:

server.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, cs, len;

    struct sockaddr_in srv_addr, cli_addr;

    char buf[64];

 

    /* Address and port to listen on */

    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 listen */

    s = socket(AF_INET, SOCK_STREAM, 0);

    bind(s, (struct sockaddr *)&srv_addr, sizeof(srv_addr));

    listen(s, 1);

 

    /* Wait for a new client connection */

    printf(“Waiting for a client…\n”);

    len = sizeof(cli_addr);

    cs = accept(s, (struct sockaddr*)&cli_addr, &len);

 

    /* Handle the connection */

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

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

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

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

 

    /* Done */

    close(cs);

    close(s);

    return 0;

}

This code first defines an address for binding the server socket.  Next it creates a TCP socket and binds it to that address.  After this it waits for a client to connect.  In this example the ‘accept’ function will not return until a client connection is established.  The return value is a new socket that can be used to communicate with the client.  This example writes a single message and then reads a single message.  After the messages are exchanged, the sockets are closed and the program exits.