Mikhail T. Mikhail T. - 1 year ago 167
Ruby Question

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

I have an object, which pprints into:

#<OpenSSL::ASN1::ASN1Data:0x0000000803ab37a8
@infinite_length=false,
@tag=7,
@tag_class=:CONTEXT_SPECIFIC,
@value="\x7F\x00\x00\x01">]>


It is easy enough to see, that the
@value
is an IP-address: 127.0.0.1. 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(':')
        else
            STDERR.print "The encountered IP-address is neither IPv4 nor IPv6\n"
            next
        end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download