Nick Ananiev
Nick Ananiev

Reputation: 13

Bind UDP server on specific ip address ERLANG

I need to bind the UDP server to a specific IP address. Now I'm creating a UDP server like this

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}}.

Where PARAM is UDP server port. I don't know how to bind it to some IP. Could someone help me please?

Upvotes: 1

Views: 212

Answers (1)

legoscia
legoscia

Reputation: 41527

Use the ip option, passing the address as a tuple:

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

If you have the IP address in string format, you can use inet:parse_address/1 to parse it into a tuple:

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

Upvotes: 2

Related Questions