[erlang-questions] Differentiating between FQDN and IP addresses

zxq9 zxq9@REDACTED
Fri Aug 18 17:00:38 CEST 2017


On 2017年08月18日 金曜日 20:00:24 Sachin Joshi wrote:
> I am getting an input  in a program as 'ip address' or 'FQDN'. I need to
> identify if it is an ipv4 or ipv6 or a hostname(fqdn).
> Can someone help me in this?

Hi, Sachin.


I'm assuming you are receiving these as strings.

The function inet:parse_strict_address/1 can help you determine if the string is a valid IPv4, IPv6, or invalid IP address.
http://erlang.org/doc/man/inet.html#parse_strict_address-1

If it is an invalid IP address, then attempt to use it as a FQDN instead. If that fails, then perhaps it is invalid in general.

As for "what is a valid FQDN?" the standard has slid a lot in recent years, so it seems more common to just try it out (perhaps converting a utf-8 string via punycode first to see if that fails) and see if it barfs or not.

Imagine something along the lines of...

> -spec interpret_address(string()) -> Result
>    when Result :: {ipv4, inet:ipv4_address()}
>                 | {ipv6, inet:ipv6_address()}
>                 | {fqdn, inet:hostname()}.
>
> interpret_address(String) ->
>     case inet:parse_strict_address(String) of
>         {A, B, C, D} ->
>             {ipv4, {A, B, C, D}};
>         {A, B, C, D, E, F, G, H} ->
>             {ipv6, {A, B, C, D, E, F, G, H}};
>         {error, einval} ->
>             {fqdn, String}
>     end.


With the exception that the result on {error, einval} should really look like:

> {error, einval} ->
>     validate_fqdn(String)

and the overall function should be allowed to return the type

> Result :: {ipv4, inet:ipv4_address()}
>         | {ipv6, inet:ipv6_address()}
>         | {fqdn, inet:hostname()}
>         | {error, bad_address}.

But you can get the effect of this by just trying the return value of {fqdn, String} and see if it can actually resolve a hostname this way.

Or something like that.

Forgive my imprecision -- it is very late here. Hopefully this points you in the right direction.

-Craig



More information about the erlang-questions mailing list