IP address representation inconsistencies in Socket

D

David G. Andersen

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
 
T

ts

D> so you could take the output of gethostbyname and feed it into
D> gethostbyaddr (as the example in the Pickaxe book does). But
D> this no longer works in 1.8. As it is, one has to take the output,
D> unpack the sockaddr output:

Dave Thomas has seen this problem and it's now corrected in the CVS
version.


Guy Decoux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top