Skip to content

Instantly share code, notes, and snippets.

@stevenproctor
Created July 9, 2015 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenproctor/38177ebee5e601e4e153 to your computer and use it in GitHub Desktop.
Save stevenproctor/38177ebee5e601e4e153 to your computer and use it in GitHub Desktop.
Elixir Experience Problem 15

Problem: 15

Erlang :gen_tcp.connect/3‘s first argument(Address) is either an :inet.ip_address() which is a tuple of octets or an :inet.hostname() which is a char_list. Write a function format_host that takes a string a returns a valid format for :gen_tcp.connect

format_host("192.168.0.1") #=> {192, 168, 0, 1}
  format_host("www.example.com") #=> 'www.example.com'

How about using interop with Erlang to handle a solved problem for you, and take advantage of :inet.parse_strict_address. This solution would also handle IPv6 addresses as well. ;)

def format_host(host_address) do
  address = to_char_list(host_address)
  case :inet.parse_strict_address(address) do
    {:ok, parsed_address} ->
      parsed_address
    _ ->
      address
  end
end

Problem 15 solution from elixirexperince.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment