user180574
user180574

Reputation: 6084

Ruby: how to convert IP address from hex string to human readable?

Not able to find it, apologize in advance if duplicate.

I want to convert address like,

0000000000000000FFFF00000B79290A

into human readable form. Note, although it is IPv6, it is actually IPv4 address embedded, so more preferably to have it converted to like:

10.41.121.11

I read this type of address from /proc/net/tcp, and would like to parse it.

Thank you.

Upvotes: 2

Views: 1157

Answers (1)

the Tin Man
the Tin Man

Reputation: 160549

Ruby comes with the IPAddr class which can parse IPv4 and IPv6 strings into objects. There's also NetAddr which is very powerful. Use the pre-invented wheels when possible as they're well tested and include useful methods:

require 'ipaddr'
IPAddr.new "[#{'0000000000000000FFFF00000B79290A'.scan(/.{4}/).join(':')}]"
#<IPAddr: IPv6:0000:0000:0000:0000:ffff:0000:0b79:290a/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>

It's necessary to convert the string to colon-delimited fields, and wrapping it in [...] tells IPAddr to consider it an IPv6 address:

'0000000000000000FFFF00000B79290A'.scan(/.{4}/)
=> [
    [0] "0000",
    [1] "0000",
    [2] "0000",
    [3] "0000",
    [4] "FFFF",
    [5] "0000",
    [6] "0B79",
    [7] "290A"
]

'0000000000000000FFFF00000B79290A'.scan(/.{4}/).join(':')
=> "0000:0000:0000:0000:FFFF:0000:0B79:290A"

Using NetAddr:

NetAddr::CIDR.create('0000000000000000FFFF00000B79290A'.scan(/.{4}/).join(':'))
=> #<NetAddr::CIDRv6:0x007fd4971c34f0 @ip=18446462598925330698, @version=6, @address_len=128, @all_f=340282366920938463463374607431768211455, @netmask=340282366920938463463374607431768211455, @network=18446462598925330698, @hostmask=0, @tag={}, @wildcard_mask=340282366920938463463374607431768211455>

Upvotes: 5

Related Questions