简体   繁体   中英

How to get current device IP using Elixir/Nerves

I'm writing a UPnP adapter for a Nerves project and as such need to be able to respond to certain requests with the devices IP address. Is there an easy one-liner way of doing so?

My project is using VintageNet along with nerves-pack , and it is possible to get the IP through VintageNet properties. However, VintageNet does not work during development on the host, and this is important to me to be able to debug my UPnP implementation. Also, this makes it awkward to make my UPnP library independent from nerves in the future.

Thanks for the help.

Not sure about Nerves, but you can use the output of :inet.getifaddrs/0 to get the information you need.

For example, if you knew you wanted the IPv4 address of adapter en1 :

:inet.getifaddrs()
|> elem(1)
|> Map.new()
|> Map.get('en1')
|> Keyword.get_values(:addr)
|> Enum.find(&match?({_, _, _, _}, &1))

Example output:

{192, 168, 0, 1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM