【问题标题】:Bind UDP server on specific ip address ERLANG在特定 IP 地址 ERLANG 上绑定 UDP 服务器
【发布时间】:2021-01-20 01:26:06
【问题描述】:

我需要将 UDP 服务器绑定到特定的 IP 地址。现在我正在创建一个这样的 UDP 服务器

start_link(N,Param) ->
  gen_server:start_link({local,?SERVER},?MODULE, [N,Param], []).

%% ------------------------------------------------------------------
%% gen_server Function Definitions
%% ------------------------------------------------------------------

%% opens UDP listening socket. May be sockets will be more than 1
init([N,ListenPort]) ->
  Port=ListenPort+N-1,
  inets:start(),
  {ok,Socket}=gen_udp:open(Port,[{active,once},{reuseaddr,true},binary]),
  {ok, #state{port=Port,socket=Socket,in=0,out=0}}.

其中 PARAM 是 UDP 服务器端口。 我不知道如何将它绑定到某个IP。 有人可以帮帮我吗?

【问题讨论】:

    标签: udp erlang erlang-otp


    【解决方案1】:

    使用ip 选项,将地址作为元组传递:

    {ok,Socket}=gen_udp:open(Port,[{active,once},{reuseaddr,true},binary,{ip,{127,0,0,1}}]),
    

    如果你有字符串格式的IP地址,可以使用inet:parse_address/1解析成元组:

    {ok, IpAddress} = inet:parse_address("127.0.0.1"),
    {ok,Socket}=gen_udp:open(Port,[{active,once},{reuseaddr,true},binary,{ip,IpAddress}]),
    

    【讨论】:

      猜你喜欢
      • 2023-02-12
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2015-02-21
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多