編集履歴ページに戻る
+ せっかくだから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(IPMSG_SENDCHECKOPT, 16#100).
-define(DEFAULT_UDP_OPTS, [
{active, false},
+ % {broadcast, true},
+ {reuseaddr, true}
- % {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])).
- 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),
- EntMsg = send_format(Num, "local", "erlang", ?IPMSG_SENDMSG, Msg),
- io:format("send ~s port ~w~n", [EntMsg, ?IPMSG_DEFAULT_PORT]),
gen_udp:send(Socket, Host, ?IPMSG_DEFAULT_PORT, EntMsg),
-
gen_udp:close(Socket);
Error ->
Error
end.
}}}