Jump to content

C Programming/Networking in UNIX

From Wikibooks, open books for an open world
Previous: Complex types C Programming Next: Common practices

Network programming under UNIX is relatively simple in C.

This guide assumes you already have a good general idea about C, UNIX and networks.


A simple client

[edit | edit source]

To start with, we'll look at one of the simplest things you can do: initialize a stream connection and receive a message from a remote server.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
 
#define MAXRCVLEN 500
#define PORTNUM 2300
 
int main(int argc, char *argv[])
{
   char buffer[MAXRCVLEN + 1]; /* +1 so we can add null terminator */
   int len, mysocket;
   struct sockaddr_in dest; 
 
   mysocket = socket(AF_INET, SOCK_STREAM, 0);
  
   memset(&dest, 0, sizeof(dest));                /* zero the struct */
   dest.sin_family = AF_INET;
   dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* set destination IP number - localhost, 127.0.0.1*/ 
   dest.sin_port = htons(PORTNUM);                /* set destination port number */
 
   connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr_in));
  
   len = recv(mysocket, buffer, MAXRCVLEN, 0);
 
   /* We have to null terminate the received data ourselves */
   buffer[len] = '\0';
 
   printf("Received %s (%d bytes).\n", buffer, len);
 
   close(mysocket);
   return EXIT_SUCCESS;
}

This is the very bare bones of a client; in practice, we would check every function that we call for failure, however, error checking has been left out for clarity.

As you can see, the code mainly revolves around dest which is a struct of type sockaddr_in. This struct stores information about the machine we want to connect to.

mysocket = socket(AF_INET, SOCK_STREAM, 0);

The socket() function tells our OS that we want a file descriptor for a socket which we can use for a network stream connection; what the parameters mean is mostly irrelevant for now.

memset(&dest, 0, sizeof(dest));                /* zero the struct */
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1"); /* set destination IP number */ 
dest.sin_port = htons(PORTNUM);                /* set destination port number */

Now we get on to the interesting part:

The first line uses memset() to zero the struct.

The second line sets the address family. This should be the same value that was passed as the first parameter to socket(); for most purposes AF_INET will serve.

The third line is where we set the IP of the machine we need to connect to. The variable dest.sin_addr.s_addr is just an integer stored in Big Endian format, but we don't have to know that as the inet_addr() function will do the conversion from string into Big Endian integer for us.

The fourth line sets the destination port number. The htons() function converts the port number into a Big Endian short integer. If your program is going to be run solely on machines which use Big Endian numbers as default then dest.sin_port = 21 would work just as well. However, for portability reasons htons() should always be used.

Now that all of the preliminary work is done, we can actually make the connection and use it:

connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr_in));

This tells our OS to use the socket mysocket to create a connection to the machine specified in dest.

len = recv(mysocket, buffer, MAXRCVLEN, 0);

Now this receives up to MAXRCVLEN bytes of data from the connection and stores them in the buffer string. The number of characters received is returned by recv(). It is important to note that the data received will not automatically be null terminated when stored in the buffer, so we need to do it ourselves with buffer[len] = '\0'.

And that's about it!

The next step after learning how to receive data is learning how to send it. If you've understood the previous section then this is quite easy. All you have to do is use the send() function, which uses the same parameters as recv(). If in our previous example buffer had the text we wanted to send and its length was stored in len we would write send(mysocket, buffer, len, 0). send() returns the number of bytes that were sent. It is important to remember that send(), for various reasons, may not be able to send all of the bytes, so it is important to check that its return value is equal to the number of bytes you tried to send. In most cases this can be resolved by resending the unsent data.

A simple server

[edit | edit source]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>

// --- Macros & Definitions ---
#define PORTNUM 2300
#define BUFSIZE 1024

#define GF_FILE_NOT_FOUND 404
#define GF_ERROR 500
#define GF_OK 200

// --- Type Declarations ---

/* A minimal connection context, here simply a socket descriptor */
typedef struct connection_context {
    int sock;
} connection_context;

/* Request structure as used by the worker threads */
typedef struct steque_request {
    char *filepath;
    connection_context context;
} steque_request;

/* A simple linked-list node for our work queue */
typedef struct request_node {
    steque_request *request;
    struct request_node *next;
} request_node;

/* The work queue structure */
typedef struct request_queue {
    request_node *head;
    request_node *tail;
} request_queue;

// --- Global Variables for Multithreading ---
pthread_mutex_t mutex;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
request_queue *work_queue = NULL;  // Global work queue pointer

// --- Steque (Work Queue) Helper Functions ---

/* Returns nonzero if the queue is empty */
int steque_isempty(request_queue *q) {
    return (q->head == NULL);
}

/* Removes and returns the request at the front of the queue */
steque_request *steque_pop(request_queue *q) {
    if (q->head == NULL)
        return NULL;
    request_node *node = q->head;
    steque_request *req = node->request;
    q->head = node->next;
    if (q->head == NULL)
        q->tail = NULL;
    free(node);
    return req;
}

/* Pushes (enqueues) a request onto the back of the queue */
void steque_push(request_queue *q, steque_request *req) {
    request_node *node = malloc(sizeof(request_node));
    if (!node) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    node->request = req;
    node->next = NULL;
    if (q->tail == NULL) {  // Queue is empty
        q->head = q->tail = node;
    } else {
        q->tail->next = node;
        q->tail = node;
    }
}

// --- Stub Helper Functions for File Handling & Sending ---

/* Clears the given buffer */
void clear_buffer(char *buf, size_t buflen) {
    memset(buf, 0, buflen);
}

/* Opens the file specified by filepath; returns its file descriptor */
int content_get(const char *filepath) {
    return open(filepath, O_RDONLY);
}

/* Sends a header over the connection; here it builds a simple header string */
int gfs_sendheader(connection_context *ctx, int status, size_t size) {
    char header[256];
    snprintf(header, sizeof(header), "Status: %d, Size: %zu\n", status, size);
    return send(ctx->sock, header, strlen(header), 0);
}

/* Sends the buffer over the connection */
ssize_t gfs_send(connection_context *ctx, const char *buf, size_t len) {
    return send(ctx->sock, buf, len, 0);
}

void set_pthreads(size_t nthreads){
  pthread_t threads[nthreads];
  int res = pthread_mutex_init(&mutex, NULL);
  if (res != 0)
    exit(92);
  for (int i = 0; i < nthreads; i++) {
    res = pthread_create(&threads[i], NULL, thread_handle_req, NULL);
    if (res != 0)
      exit(34);
  }
}

void *thread_handle_req(void *arg) {
  int fd, fstats;
  char buf[BUFSIZE];
  struct stat finfo;
  steque_request *req;
  size_t total_bts_sent, bts_sent, bts_read, file_len;

  clear_buffer(buf, BUFSIZE);

  for(;;){
    // mutex lock
    if (pthread_mutex_lock(&mutex) != 0)
      exit(12);

    // do nothing while queue is empty
    while (steque_isempty(work_queue))
      pthread_cond_wait(&cond, &mutex);

    // get a request from the queue 
    req = steque_pop(work_queue);

    // mutex unlock
    if (pthread_mutex_unlock(&mutex))
      exit(29);

    // signal to other threads
    pthread_cond_signal(&cond);

    // send file 
    // start by getting the filepath 
    fd = content_get(req->filepath);
    // check if you have found the file 
    if (fd == -1){
      gfs_sendheader(&req->context, GF_FILE_NOT_FOUND, 0);
      break;
    } 
    // file was found, now get stats
    fstats = fstat(fd, &finfo);
    // check if error when getting stats
    if (fstats == -1) {
      gfs_sendheader(&req->context, GF_ERROR, 0);
      close(fd);
      break;
    }

    // everything ok, send header
    gfs_sendheader(&req->context, GF_OK, finfo.st_size);
    
    // send everything 
    total_bts_sent = 0;
    bts_sent = 0;
    bts_read = 0;
    file_len = finfo.st_size;
    do {
      clear_buffer(buf, BUFSIZE);
      bts_read = pread(fd, buf, BUFSIZE, total_bts_sent);
      if(!(bts_read > 0))
        break;
      bts_sent = gfs_send(&req->context, buf, bts_read);
      total_bts_sent += bts_sent;
    } while(file_len > total_bts_sent);

    // free resources
    free(req);
  }
  free(req);
  return 0;
}

// --- Main Server Code ---
int main(int argc, char *argv[])
{
    int server_sock, client_sock;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);

    // Allocate and initialize the global work queue
    work_queue = malloc(sizeof(request_queue));
    if (!work_queue) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    work_queue->head = work_queue->tail = NULL;

    // Set up the listening socket
    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock < 0) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORTNUM);

    if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind");
        close(server_sock);
        exit(EXIT_FAILURE);
    }

    if (listen(server_sock, 10) < 0) {
        perror("listen");
        close(server_sock);
        exit(EXIT_FAILURE);
    }
    printf("Server listening on port %d...\n", PORTNUM);

    // Start worker threads (using 4 threads in this example)
    set_pthreads(4);

    // Main accept loop: for each incoming connection, create a request and enqueue it
    while (1)
    {
        client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_sock < 0) {
            perror("accept");
            continue;
        }
        printf("Accepted connection from %s\n", inet_ntoa(client_addr.sin_addr));

        // Create a new request for the connection.
        // Here we always send the same file ("hello.txt").
        steque_request *req = malloc(sizeof(steque_request));
        if (!req) {
            perror("malloc");
            close(client_sock);
            continue;
        }
        req->filepath = strdup("hello.txt");
        if (!req->filepath) {
            perror("strdup");
            free(req);
            close(client_sock);
            continue;
        }
        req->context.sock = client_sock;

        // Enqueue the request in a thread-safe manner
        if (pthread_mutex_lock(&mutex) != 0) {
            perror("pthread_mutex_lock");
            free(req->filepath);
            free(req);
            close(client_sock);
            continue;
        }
        steque_push(work_queue, req);
        pthread_cond_signal(&cond);
        if (pthread_mutex_unlock(&mutex) != 0) {
            perror("pthread_mutex_unlock");
            continue;
        }
    }

    close(server_sock);
    return 0;
}

Superficially, this is very similar to the client. The first important difference is that rather than creating a sockaddr_in with information about the machine we're connecting to, we create it with information about the server, and then we bind() it to the socket. This allows the machine to know the data received on the port specified in the sockaddr_in should be handled by our specified socket.

The listen() function then tells our program to start listening using the given socket. The second parameter of listen() allows us to specify the maximum number of connections that can be queued. Each time a connection is made to the server it is added to the queue. We take connections from the queue using the accept() function. If there is no connection waiting on the queue the program waits until a connection is received. The accept() function returns another socket. This socket is essentially a "session" socket, and can be used solely for communicating with connection we took off the queue. The original socket (mysocket) continues to listen on the specified port for further connections.

Once we have "session" socket we can handle it in the same way as with the client, using send() and recv() to handle data transfers.

Note that this server can only accept one connection at a time; if you want to simultaneously handle multiple clients then you'll need to fork() off separate processes, or use threads, to handle the connections.

Useful network functions

[edit | edit source]
int gethostname(char *hostname, size_t size);

The parameters are a pointer to an array of chars and the size of that array. If possible, it finds the hostname and stores it in the array. On failure it returns -1.

struct hostent *gethostbyname(const char *name);

This function obtains information about a domain name and stores it in a hostent struct. The most useful part of a hostent structure is the (char**) h_addr_list field, which is a null terminated array of the IP addresses associated with that domain. The field h_addr is a pointer to the first IP address in the h_addr_list array. Returns NULL on failure.

What about stateless connections?

[edit | edit source]

If you don't want to exploit the properties of TCP in your program and would rather just use a UDP connection, then you can just replace SOCK_STREAM with SOCK_DGRAM in your call to socket() and use the result in the same way. It is important to remember that UDP does not guarantee delivery of packets and order of delivery, so checking is important.

If you want to exploit the properties of UDP, then you can use sendto() and recvfrom(), which operate like send() and recv() except you need to provide extra parameters specifying who you are communicating with.

How do I check for errors?

[edit | edit source]

The functions socket(), recv() and connect() all return -1 on failure and use errno for further details.

Previous: Complex types C Programming Next: Common practices