Parse IPV4 or IPV6 bitstrings

Hi, I’am parsing OTPCertificates obtain with :ssl.
Some alternative names has IPV4 or IPV6 bitstrings like:

[
  iPAddress: <<1, 1, 1, 1>>,
  iPAddress: <<1, 0, 0, 1>>,
  iPAddress: <<162, 159, 132, 53>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 1>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100>>,
  iPAddress: <<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0>>,
  iPAddress: <<162, 159, 36, 1>>,
  iPAddress: <<162, 159, 46, 1>>
]

I successfully translated IPV4 ones (Ex: “162.159.132.53”) with this code:

            <<162, 159, 132, 53>>
            |> :unicode.characters_to_binary(:latin1, :utf8)
            |> to_charlist()
            |> List.to_tuple()
            |> :inet_parse.ntoa()
            |> to_string()

But I couldn’t translate IPV6. Any ideas?

<<38, 6, 71, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17>> should translate to “2606:4700:4700:0:0:0:0:1111”

You may want to use binary comprehensions, for both v4 and v6:

for <<field <- ipv4>> do field end
|> List.to_tuple()
|> :inet.ntoa()
|> to_string()
for <<group::16 <- ipv6>> do group end
|> List.to_tuple()
|> :inet.ntoa()
|> to_string()

Note that inet_parse is an internal, undocumented module: use the public inet:ntoa/1 instead.

5 Likes

Thanks!