Wednesday, September 26, 2007

BSD Sockets in Ruby

I love Ruby. Completely. I don't want to write in anything else. However, meeting with the BSD sockets interface left me with a sour taste. Here's what I learned. Hopefully, you'll find this post and won't waste time if you have to work with Ruby's sockets.

You can send packets with sendThe method name is good for consistency, but a horrible choice in general, if you ask me, because it overrides send in Object (used to send a message to an object, same thing as calling a method).

send's parameters are a string representing the data (same encoding as in recv), and a number for flags. The number is NOT optional (messed up choice, in my opinion), so my sockets code always has send data, 0 in it.

send fails oddlyIf you're seeeing in `send': symbol string may not contain `\0' (ArgumentError) then your socket is object is null. This happens because nil uses Object's send, so it thinks you're passing it a method name.

pack_sockaddr_in doesn't like localhostSilly me, I looked the example using www.google.com and I thought I can give pack_sockaddr_in any address. If I give it localhost, I get in `connect': Invalid argument - connect(2) (Errno::EINVAL).Solution: use 127.0.0.1

Using strings for send / recv is annoyingIf I'm using sockets, I'm working at the byte level. Using Fixnum arrays to represent bytes in a packet is a lot more convenient than using strings. Here are snippers for converting between the two formats. (I did Scheme at MIT, so I love map-reduce... I meant, collect-inject).

Short Bio

Victor Costan got infected with a passion for coding at the age of 10, and proceeded to earn a M.Eng in Computer science from MIT. Victor also holds a B.S. in Management that he pursued as he fell prey to the belief that great software requires legions of developers manipulating bloated code bases in repetitive ways. Thanks to Paul Graham's essays, Ruby, and Rails, he re-discovered the joy of coding, and came back from the dark ways of management.

Nowadays, Victor is still crazy about building software that he can impress his friends with, but he also dreams of contributing to making coding even more enjoyable. Victor likes developing mobile and Web 2.0 applications, and occasionally enjoys building some distributed systems behind the apps. When he is not coding, you will most likely find him reading up on some new programming language or software development technique.

At times, Victor likes to pretend he's mentally sane, and can be seen catching up with friends, watching a movie, or exploring Boston.