61 byte selection sort

Here's the absolutely smallest array sorting function in C. It's written by M. Doughlas McIlroy of Darthmouth College, NH USA. It only 67 bytes long (ignoring new-line characters), which is ridiculously impressive. In the function s shown below, a is the starting address of the array, and b is the address of the last element plus one.


This can be made even smaller using recursion and by inferring the type specifiers of global object declarations, which is a GCC hack. In the following function, n is the number of elements in the array a.

Continue reading →

Network packets with Python

Next week, I'll have to start a project on implementing RIP (Routing Information Protocol) using UDP sockets in C. I needed a quick way to get the byte structure of RIP packets, and decided to use scapy. It's quite a handy tool and has a simple interface, which is nothing more than an extended Python shell. Auto-completion is supported out-of-the-box, which is good news for all the command-line enthusiasts out there. Here's how we dump an RIP packet straight to a PDF file.

$ scapy
Welcome to Scapy (2.3.3)
>>> entry = RIPEntry(addr='', nextHop='', mask='')
###[ RIP entry ]###
  AF= IP
  RouteTag= 0
  metric= 1

>>> r = RIP() / entry
>>> r.pdfdump()

This generates a self-explanatory packet dump. You could also use a different reader; just change the conf.prog.pdfreader object.

Continue reading →

__name__ and HTTP servers

The __name__ built-in Python variable which describes exactly that - it's the name of the module during runtime. Python modules use this variable to perform a particular action when the module is run, and probably do something else when imported by another module. It also facilitates module testing if you think about it.

Ideally, every Python module that is intended to be reused must have something like this in it, preferably at the end.

if __name__ == "__main__":
    print "Just got executed!"
    print "Got imported! I'm so cool!"
Continue reading →