Mikhail T. Mikhail T. - 3 years ago 255
Ruby Question

How to turn OpenSSL::ASN1::ASN1Data into IP-address?

I have an object, which pprints into:


It is easy enough to see, that the
is an IP-address: How do I reliably extract it, however -- so that it works regardless of endianness and other hard-to-test considerations?

I'm doing it the following way for now:

ip = v.value.split('').map {|octet| octet.ord }.join('.')

and it works on my machine, but I wonder, how reliable the method is...

Answer Source

Ok, as I report in a related question, I found an answer in Ruby's own code (openssl/ssl.rb). They deal with both IPv4 and IPv6 addresses thus -- using unpack instead of split-ing the string into characters:

        case v.value.size
        when 4
            ip = v.value.unpack('C*').join('.')
        when 16
            ip = v.value.unpack('n*').map { |o| sprintf("%X", o) }.join(':')
            STDERR.print "The encountered IP-address is neither IPv4 nor IPv6\n"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download