Listen for Bonjour / ZeroConf traffic in Erlang


/ Published in: Other
Save to your folder(s)

This now not only listens but can send requests


Copy this code and paste it in your HTML
  1. -module(zeroconf).
  2.  
  3. -include("zeroconf.hrl").
  4.  
  5. -export([open/2,start/0]).
  6. -export([stop/1,receiver/0]).
  7. -export([send/1]).
  8.  
  9.  
  10. send(Domain) ->
  11. {ok,S} = gen_udp:open(5353,[{reuseaddr,true}, {ip,{224,0,0,251}}, {multicast_ttl,4}, {multicast_loop,false}, {broadcast,true}, binary]),
  12. P = #dns_rec{header=#dns_header{},qdlist=[#dns_query{domain=Domain,type=ptr,class=in}]},
  13. gen_udp:send(S,{224,0,0,251},5353,inet_dns:encode(P)),
  14. gen_udp:close(S).
  15.  
  16. open(Addr,Port) ->
  17. {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]),
  18. inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]),
  19. S.
  20.  
  21. close(S) -> gen_udp:close(S).
  22.  
  23. start() ->
  24. S=open({224,0,0,251},5353),
  25. Pid=spawn(?MODULE,receiver,[]),
  26. gen_udp:controlling_process(S,Pid),
  27. {S,Pid}.
  28.  
  29. stop({S,Pid}) ->
  30. close(S),
  31. Pid ! stop.
  32.  
  33. receiver() ->
  34. receive
  35. {udp, _Socket, IP, InPortNo, Packet} ->
  36. io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]),
  37. receiver();
  38. stop -> true;
  39. AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]),
  40. receiver()
  41. end.

URL: http://www.vertigrated.com/blog/2009/11/bonjour-zeroconf-in-erlang/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.