[トップ][ノート][編集履歴][一覧][最近の更新][->English]

Programming/Erlang/2008/02/26/udpmsg

Category of Programming
Category of Erlang

せっかくだからErlang版も貼っとく。 じつはずっと昔に書いたコードだったりする。

-module(udpmsg).
-export([send/2]).

-include_lib("kernel/include/inet.hrl").

-define(IPMSG_VERSION,      16#0001).
-define(IPMSG_DEFAULT_PORT, 16#0979).
-define(IPMSG_SENDMSG,      16#020).

-define(DEFAULT_UDP_OPTS, [
                           {active, false},
%                          {broadcast, true},
                           {reuseaddr, true}
                          ]).

send_format(Num, Host, User, Cmd) ->
    lists:flatten(io_lib:format("~.10b:~.10b:~s:~s:~.10b:",   [?IPMSG_VERSION, Num, User, Host, Cmd])).
send_format(Num, Host, User, Cmd, Extra) ->
    lists:flatten(io_lib:format("~.10b:~.10b:~s:~s:~.10b:~s", [?IPMSG_VERSION, Num, User, Host, Cmd, Extra])).

send(Host, Msg) ->
    Num = erlang:phash(erlang:localtime(), 16777215),
    case gen_udp:open(0, ?DEFAULT_UDP_OPTS) of
        {ok, Socket} ->
            EntMsg = send_format(Num, "myhost", "myname", ?IPMSG_SENDMSG, Msg),
            gen_udp:send(Socket, Host, ?IPMSG_DEFAULT_PORT, EntMsg),
            gen_udp:close(Socket);
        Error ->
            Error
    end.
blog comments powered by Disqus