One post is tagged with network.

There is an Atom feed for posts tagged with network.

Raw Sockets

2006-11-22 Tags: , ,

Python is sometimes described as "just a scripting language". This show how much some people want to separate all programming languages into two or three categories without even knowing what they are talking about.

One nice thing about Python is the way it exposes the Unix internals. Almost all the system calls have bindings with interface so close to C that you can follow the man pages when using them. Of course, efficiency is not always there but you can sketch out a solution in no time and fall back to C when the profiler tells you to do so.

The socket API is exposed in all its gory details and it possible to do raw sockets: to build each packets byte by byte including the headers. The C API uses unions that are casted as struct when an individual field needs to be set and casted as byte array when written on the wire. The Python API uses string objects which makes it a bit painful to set a single field but poses no problems when building the packets from scratch.

As an example, its is possible to implement ping in just over 100 lines. Using time.time(), we don't have enough resolution to make accurate reading for round trips under ~5ms but it still works pretty much as expected otherwise. Note that if you are to try it you'll need to be root since it's the only way to access raw sockets (the real ping is setuid).

A new non baroque language should aim to be as cleaver as Python in exposing the host platform internals. CL+UFFI is not bad, SBCL's sb-posix is especially nice. Skilled use of macros makes the whole binding set easy to read and to maintain:

       (define-call "link" int minusp (oldpath filename) 
                                      (newpath filename))
       (define-call "lseek" sb-posix::off-t minusp (fd file-descriptor) 
                                                   (offset sb-posix::off-t) 
                                                   (whence int))
       (define-call "mkdir" int minusp (pathname filename) 
                                       (mode sb-posix::mode-t))
       (define-call "mkstemp" int minusp (template c-string))
       (define-call "sync" void never-fails)