aboutsummaryrefslogtreecommitdiff
path: root/shard/lib/net/addr.ex
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2018-10-12 22:11:45 +0200
committerAlex Auvolat <alex@adnab.me>2018-10-12 22:11:45 +0200
commiteab3f9483b3659b1ad3572393d24652cac71c8b6 (patch)
treed8066ff0c173ef74bb9758707d8428a5f922bd8b /shard/lib/net/addr.ex
parent574b572fac144135c4381581351445bf5d0de81c (diff)
downloadshard-eab3f9483b3659b1ad3572393d24652cac71c8b6.tar.gz
shard-eab3f9483b3659b1ad3572393d24652cac71c8b6.zip
fixes to connection logic
Diffstat (limited to 'shard/lib/net/addr.ex')
-rw-r--r--shard/lib/net/addr.ex32
1 files changed, 24 insertions, 8 deletions
diff --git a/shard/lib/net/addr.ex b/shard/lib/net/addr.ex
index 630f95a..c1d2f05 100644
--- a/shard/lib/net/addr.ex
+++ b/shard/lib/net/addr.ex
@@ -1,4 +1,25 @@
defmodule SNet.Addr do
+ use Agent
+
+ require Logger
+
+ def start_link(_) do
+ Agent.start_link(__MODULE__, :init, [], name: __MODULE__)
+ end
+
+ def init() do
+ Application.ensure_all_started(:inets)
+ Application.ensure_all_started(:ssl)
+ case :httpc.request('http://api.ipify.org') do
+ {:ok, {_, _, body}} ->
+ {:ok, addr} = :inet.parse_address body
+ Logger.info "Public IP address: #{body}"
+ [addr]
+ _ ->
+ Logger.info "Could not get public IP address"
+ []
+ end
+ end
def get_if_inet4 do
{:ok, ifs} = :inet.getifaddrs
@@ -12,20 +33,15 @@ defmodule SNet.Addr do
end
def get_pub_inet4 do
- Application.ensure_all_started(:inets)
- Application.ensure_all_started(:ssl)
- {:ok, {_, _, body}} = :httpc.request('http://api.ipify.org')
- {:ok, addr} = :inet.parse_address body
- addr
+ Agent.get(__MODULE__, &(&1))
end
def get_all_inet4 do
- addrset = for x <- get_if_inet4(), into: %MapSet{}, do: x
- addrset = MapSet.put(addrset, get_pub_inet4())
+ addrset = for x <- get_if_inet4() ++ get_pub_inet4(), into: %MapSet{}, do: x
MapSet.to_list addrset
end
def is_local?({:inet, ip, port}) do
- port == Application.get_env(:shard, :port) and (ip == {127,0,0,1} or ip in get_if_inet4())
+ port == Application.get_env(:shard, :port) and (ip == {127,0,0,1} or ip in get_all_inet4())
end
end