[erlang-questions] Finding IP addresses in a PC

Surindar Sivanesan surindar.shanthi@REDACTED
Wed Oct 4 06:20:45 CEST 2006


The following code might return the correct IP by calling ip:list() from erl
shell



-module(ip).
-export([list/0]).

list()->
 IpAddress=inet:getiflist(),
 case IpAddress of
  {ok,IpList}->
    format_ip(IpList,[]);
  _->
   io:fwrite("Error ~p in getting ip list\n",[IpAddress])
 end.

format_ip(Iplist,FormatedList)->
 case Iplist of
  []->
   FormatedList;
  _->
   Ip=hd(Iplist),
   ReversedIp=lists:reverse(string:tokens(Ip,".")),
   FormatedIP=check_ip(ReversedIp,""),
   format_ip(tl(Iplist),FormatedList++[FormatedIP])
 end.

check_ip(IpList,Return)->
 case IpList of
  []->
   Return;
  _->
   IpPart=lists:reverse(hd(IpList)),
   case length(IpPart) of
    3->
     NewPart=integer_to_list(list_to_integer(IpPart)),
     case Return of
      ""->
       check_ip(tl(IpList),Return++NewPart);
      _->
       check_ip(tl(IpList),Return++"."++NewPart)
     end;
    2->
     NewPart=integer_to_list(list_to_integer(IpPart++"0")),
     case Return of
      ""->
       check_ip(tl(IpList),Return++NewPart);
      _->
       check_ip(tl(IpList),Return++"."++NewPart)
     end;
    1->
     NewPart=integer_to_list(list_to_integer(IpPart++"00")),
     case Return of
      ""->
       check_ip(tl(IpList),Return++NewPart);
      _->
       check_ip(tl(IpList),Return++"."++NewPart)
     end;
    _->
     io:fwrite("Illegal IP length\n")
   end
 end.


On 10/3/06, Shelton Tang <shelton.ms@REDACTED> wrote:
>
> I have one NIC with the address {192,168,0,150} on my Vista machine.
> If I call inet:getiflist(),  it returns
> ["51.0.861.291","100.0.0.721"].
>
> Anybody know how to convert it to a valid format?
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



-- 
with regards,
S.Surindar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20061004/4bd11804/attachment.htm>


More information about the erlang-questions mailing list