Nov 152009
 

Here is the beginnings of a Bonjour / ZeroConf module in Erlang. I always like to ZeroConf all my servers I write so I don’t have to play the xml/properties/ini file game with how a server or clients connect to each other. All my previous Python and Java servers have used bindings to a C library to work their magic, I want to create a native Erlang module since I am trying to ween myself off Python/Twisted and onto Erlang for good. And I want to do it in a way that doesn’t require ports or linked-in libraries, I want a native Erlang solution.

zeroconf.erl

-module(zeroconf).

-include("zeroconf.hrl").

-export([open/0,start/0]).
-export([stop/1,receiver/0]).
-export([send/1]).

-define(ADDR, {224,0,0,251}).
-define(PORT, 5353).

open() ->
   {ok,S} = gen_udp:open(?PORT,[{reuseaddr,true}, {ip,?ADDR}, {multicast_ttl,4}, {multicast_loop,false}, binary]),
   inet:setopts(S,[{add_membership,{?ADDR,{0,0,0,0}}}]),
   S.

close(S) -> gen_udp:close(S).

start() ->
   S=open(),
   Pid=spawn(?MODULE,receiver,[]),
   gen_udp:controlling_process(S,Pid),
   {S,Pid}.

stop({S,Pid}) ->
   close(S),
   Pid ! stop.

receiver() ->
   receive
       {udp, _Socket, IP, InPortNo, Packet} ->
           io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]),
           receiver();
       stop -> true;
       AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]),
           receiver()
   end.

zeroconf.hrl ( these were taken directly from inet_dns.hrl )

-record(dns_header,
    {
     id = 0,       %% ushort query identification number
     %% byte F0
     qr = 0,       %% :1   response flag
     opcode = 0,   %% :4   purpose of message
     aa = 0,       %% :1   authoritive answer
     tc = 0,       %% :1   truncated message
     rd = 0,       %% :1   recursion desired
     %% byte F1
     ra = 0,       %% :1   recursion available
     pr = 0,       %% :1   primary server required (non standard)
                   %% :2   unused bits
     rcode = 0     %% :4   response code
    }).

-record(dns_rec,
    {
     header,       %% dns_header record
     qdlist = [],  %% list of question entries
     anlist = [],  %% list of answer entries
     nslist = [],  %% list of authority entries
     arlist = []   %% list of resource entries
    }).

-record(dns_query,
    {
     domain,     %% query domain
     type,        %% query type
     class      %% query class
     }).

in one console window do a

zeroconf:start().

you should start seeing traffic spewing out onto the console to issue queries for iTunes for example in another console

zeroconf:send("_daap._tcp.local.").

Sorry, the comment form is closed at this time.