This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: The secret arguments of TCPSocket
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Did you know that TCPSocket.new actually accepts up to four arguments? Well, it does. The third and fourth arguments are a local host and port, respectively. I happened across it while hunting down a bug in http.rb reported on the Mongrel mailing list, and was looking at the socket.c source.
It turns out that Matz did mention this on the mailing list...once....in 2002. I must have missed the memo.
Anyway, it lets you bind to a remote host and port from a local host and port. For example:
With that running, run a quick 'netstat -a | grep 8885'. You'll see something like this:
localhost.8885 localhost.telnet 49152 0 49152 0 ESTABLISHED
localhost.telnet localhost.8885 49152 0 49152 0 ESTABLISHED
Interesting, eh?
I did notice what I think is a bug, though. The remote connection doesn't seem to die on time - it goes into a TIME_WAIT, and I'm pretty sure it's the OS that cleans it up eventually. If you try to connect again while it's in this state, it gives you a Errno::EAFNOSUPPORT, which isn't right.
I think Nobu actually proposed a patch for this in 2002 (same thread) but I'm not sure that it was ever applied, probably because no one knew that you could pass four arguments, so (almost) no one complained.