From: "David G. Andersen" Date: 2004-06-25T03:33:59+09:00 Subject: IP address representation inconsistencies in Socket I'm curious about the "standard" form for representing IP addresses internally in Ruby (I started writing the PLEAC ruby "Internet Services" section as a way to familiarize myself with some more bits of ruby...) As far as I can tell, things in 1.8.1 are a bit inconsistent: Socket.gethostbyname ( name : string ) -> [ name : string, [ names : string ], family : fixnum, addr : string (packed sockaddr_in), rest of addrs ] Socket.gethostbyaddr ( addr : string (packed IP) ) -> [ name : string, [ names : string ], family, addr : string (packed IP) ] In 1.6, gethostbyname returned [name : string, [names : string], family : fixnum, addr : string (packed IP) ] so you could take the output of gethostbyname and feed it into gethostbyaddr (as the example in the Pickaxe book does). But this no longer works in 1.8. As it is, one has to take the output, unpack the sockaddr output: Socket.gethostbyaddr ( Socket.gethostbyname("foo")[3].unpack("snCCCa8")[2..5] ) which seems, er, somewhat sub-optimal. :) I assume that this was done to facilitate taking the output of gethostbyname and feeding it into other socket functions that want a struct sockaddr, but I think this is generally considered the purpose of getaddrinfo(). Also, there appear to be no built-in inet_ntoa or inet_aton functions. Assuming that the "right" representation of a struct in_addr is a 4-byte packed string: def inet_ntoa(addr) addr.unpack("CCCC").join(".") end def inet_aton(str) numarray = str.split(".").collect { |a| return nil if a.to_i() > 255 a.to_i() } return nil if numarray.size != 4 numarray.pack("CCCC") end The Resolv module provides the IPv4.create method that does the same thing: packed_addr_string = Resolv::IPv4.create("18.31.0.114").address but it has its own large set of problems with uninformative exceptions, and the fact that it doesn't export the standard functions that unix programmer types would want (get*by.., inet_*) Is there logic to this all that I've missed? I'd love to be able to write something up that makes sense. :) Maybe the real answer is a struct in_addr type, some day, that provides to_s and to_i methods. hm. Thanks! -Dave -- work: dga@lcs.mit.edu me: dga@pobox.com MIT Laboratory for Computer Science http://www.angio.net/