Erlang: search my IP address

I am trying to configure Load Balancer / Login Server / Game Server using Redis for some parts. Load balancing is one of them. In my Redis load balancer instance, I use ordered sets. The key is the name of the application, members are the IP addresses of the game servers.

That is my problem. I would like to use the public method in erlang. I can’t find anything that fits my needs. I wonder if I will be looking for something.

{ok, L} = inet:getif(), IP = element(1, hd(L)), 

Gives me what I'm looking for. I believe this is currently {192,168,0,14}. But the function is not "publicly available."

 {ok, Socket} = gen_tcp:listen(?PORT_LISTEN_GAME, [{active,once}, {reuseaddr, true}]), {ok, {IP, _} = inet:sockname(Socket), 

Gives me {0,0,0,0}. I tried inet:getaddr("owl") , which gives me {127,0,1,1}.

I limited myself to sending messages over TCP and using inet:peername(Socket) ? Something seems to be very simple. All the various parts of my application run on the same computer for testing. Is this going to return me {127,0,0,1}? This will not work. I need to send an IP address to a user (my mobile phone) so that they can connect to the appropriate server. Loopback would not do.

Current code

I would like to thank all the answers. Yes, I noticed a Lol4t0 comment right after the New Year. So I changed my code to reflect this. Spending this for slow people like me. I need to fit my brain a bit to make these things snap.

 hd([Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts, {flags, Flags} <- Opts, lists:member(loopback,Flags) =/= true]). 
+5
source share
2 answers

We have successfully used this function to get the first non-local IPv4 address:

 local_ip_v4() -> {ok, Addrs} = inet:getifaddrs(), hd([ Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts, size(Addr) == 4, Addr =/= {127,0,0,1} ]). 

Of course, you can change it to return IPv6 if that is what you want.

+4
source

You must first understand that your host can have more than one unique IP address. Virtually all {0,0,0,0} , {127,0,0,1} (actually all 127.0.0.0/8 are your addresses), and {192,168,0,14} are all your valid IP addresses. In addition, if other interfaces are connected on your host, you will receive even more IP addresses. Thus, you basically cannot find a function that will get your IP address that you need.

Instead, it is a well-documented function in the inet module that will list the interfaces, each with its own IP address:

 getifaddrs() -> {ok, Iflist} | {error, posix()} Types: Iflist = [{Ifname, [Ifopt]}] Ifname = string() Ifopt = {flag, [Flag]} | {addr, Addr} | {netmask, Netmask} | {broadaddr, Broadaddr} | {dstaddr, Dstaddr} | {hwaddr, Hwaddr} Flag = up | broadcast | loopback | pointtopoint | running | multicast Addr = Netmask = Broadaddr = Dstaddr = ip_address() Hwaddr = [byte()] 
+1
source

Source: https://habr.com/ru/post/1233109/


All Articles