October 1, 2011

I am always amazed at how complex network programming is in C. I've been programming with bare sockets for over a decade and I need to look up how to do it every time.

As an example of how easy it can be, here is a snippet of code to connect to a website and download the main page using python:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.codefall.com', 80))
s.send('GET / HTTP/1.1\r\nHost: www.codefall.com\r\n\r\n')
s.recv(1024)

In contrast, here is the same snippet in C:

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>

int main()
{
  struct addrinfo hints, *res;
  int st, sock = -1;

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  st = getaddrinfo("www.codefall.com", "80", &hints, &res);
  assert(st == 0);

  sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  assert(sock >= 0);

  st = connect(sock, res->ai_addr, res->ai_addrlen);
  assert(st == 0);

  freeaddrinfo(res);

  const char *msg = "GET / HTTP1.1\r\nHost: www.codefall.com\r\n\r\n";
  st = send(sock, msg, strlen(msg), 0);
  assert(st == strlen(msg));

  char buffer[1024];
  st = recv(sock, buffer, 1024, 0);
  assert(st > 0);

  close(sock);
  return 0;
}

Based on this, I can definitely see why people don't program in C unless they really, really need to...