May 3, 2012

It has been a while since I've updated this site (including any new blog posts!) so I thought I would redesign the entire thing using Node.js. You are looking at the result.

It is a very simple app which can parse the static posts from the original Octopress site. It uses Express for the routing and Stylus for the styling and most of it is written in Coffeescript.

It integrates with github to pull all the activity for a specified user and displays it in the activity list in the footer and with mailgun to send emails when interesting things happen. In the future, I would like to add twitter integration as well.

October 2, 2011

I recently was complaining about how complicated socket programming was in C - so in an effort to help my future self, I created a little wrapper around connecting and binding sockets in C.

To bind a socket to all interfaces via TCP on port 8080:

int s = connection_bind("tcp://:8080");

To bind a socket to the local interface via TCP on port 8080:

int s = connection_bind("tcp://localhost:8080");

To connect to www.codefall.com on port 80:

int s = connection_connect("tcp://www.codefall.com:80");

UDP works too:

int s = connection_bind("udp://:8080");
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...