How do I find my own IP address?

Samuel Rivas samuel@REDACTED
Thu Jan 22 16:49:24 CET 2004


Joachim Durchholz wrote:
> Samuel Rivas wrote:
> >Following your discovery I've found out an (undocumented) way to get the
> >host IP within Erlang:
> >
> >1> {ok, S} = inet_udp:open(0, []).
> >{ok,#Port<0.4112>}
> >2>prim_inet:ifget(S, "eth0", [addr]).
> >{ok,[{addr,{192,168,100,100}}]}
> 
> This will work on a vanilla Unix system.
> It will not work, for example, if you use FreeS/WAN (where the network 
> device to use would be ipsec0 for an encrypted connection, and eth0 for 
> an unencrypted one). There may be other software that installs virtual 
> network cards ("interfaces"). I'm not sure, but I suspect that even an 
> ipsec interface might have a regular IP address, including DNS entry, 
> routing table, and all.
> It will also not properly work if the machine has two network 
> interfaces. For example, I'm sitting on a desktop system that has a 
> network card (for the LAN) and an ISDN adapter that pretends to be a 
> network card. If I were running Unix, I'd have an eth0 and an eth1 card, 
> one of them with a DHCP-generated IP, the other with a local masqueraded 
> 192.168.x.x address. There's a third local network that's entirely 
> virtual, for the virtual network that serves the VMWare machines. I 
> think this kind of setup isn't too unusal for telecommuters (well, 
> except for the VMWare bit maybe... *g*)
> Oh, and I'm running Windows, which means that my machine will respond 
> with utter ignorance if you try names like /dev/eth0 on it :-)

Of course if you have more than one interface with more than one ip you
could not get *THE* host ip. And obviously if you want to know the ip of
any other interface, say loopback interface (and guess what it would be
;), this patch solves your problem:

- prim_inet:ifget(S, "eth0", [addr]).
+ prim_inet:ifget(S, "lo", [addr]).

:)

If the name of possible interfaces bothers you, there is another
(and undocumented too) function that will return an interesting list:

1> inet:getiflist(S).
{ok,["lo","eth0"]}

The real problem is those functions are not in the public API, so they
could be changed in future releases.

Finally I've no idea of how Windows names its interfaces, and no
chance to test getiflist in a Windows host ...

Regards

-- 
 ---------------------
|	Samuel        |
 ---------------------



More information about the erlang-questions mailing list