Skip to content

Commit

Permalink
Merge pull request #10 from mroach/fix_hostname_as_socket_ambiguity
Browse files Browse the repository at this point in the history
Fix hostname as socket ambiguity
  • Loading branch information
nroi authored Mar 7, 2019
2 parents 9d2446b + 556e315 commit bb99c5d
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions lib/paracusia/mpd_client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ defmodule Paracusia.MpdClient do
defp ip_addresses(hostname) do
hostname = to_charlist(hostname)

if File.exists?(hostname) do
if socket?(hostname) do
[{:local, hostname}]
else
ipv6 = {:inet6, :inet.getaddr(hostname, :inet6)}
Expand All @@ -125,6 +125,13 @@ defmodule Paracusia.MpdClient do
defp ip_string(:inet6, ip), do: :inet.ntoa(ip)
defp ip_string(:local, ip), do: ip

defp socket?(hostname) do
case File.stat(hostname) do
{:ok, %File.Stat{type: :other}} -> true
_ -> false
end
end

defp connect_retry(addrs, port, attempt, addr_idx, retry_after, max_attempts) do
if attempt > max_attempts do
reason = "Connection establishment failed, maximum number of connection attempts exceeded."
Expand All @@ -142,13 +149,15 @@ defmodule Paracusia.MpdClient do
_ -> {hostname, port}
end

target_description = "#{ip_string(addr_family, hostname)}:#{port_conn} (#{addr_family})"

case :gen_tcp.connect(hostname_conn, port_conn, opts) do
{:ok, sock} ->
_ = Logger.debug("Successfully connected to #{ip_string(addr_family, hostname)}")
_ = Logger.debug("Successfully connected to #{target_description}")
sock

{:error, :econnrefused} when next_addr_idx == 0 ->
_ = Logger.error("Connection refused, retry after #{retry_after} ms.")
_ = Logger.error("Connection to #{target_description} refused, retry after #{retry_after} ms.")
:timer.sleep(retry_after)
connect_retry(addrs, port, attempt + 1, next_addr_idx, retry_after, max_attempts)

Expand All @@ -157,7 +166,7 @@ defmodule Paracusia.MpdClient do

_ =
Logger.warn(
"Connection refused for hostname #{ip_string(addr_family, hostname)}, " <>
"Connection refused for #{target_description}, " <>
"trying #{ip_string(addr_family, next_hostname)} instead."
)

Expand Down

0 comments on commit bb99c5d

Please sign in to comment.