pandoragami
pandoragami

Reputation: 5585

Erlang gen_udp sending packets to ip address?

I tried using the following code for a simple test to send packets across the Internet. I did check to see if the localhost version works with the following commands and it did work but it doesn't work if I replace localhost (127.0.0.1) with a real internet address, mine. I just get 0 on the client side and nothing changes with the server side, although using localhost is the same with the server side.

Server side:

udp_test:start_server().

Client side:

udp_test:client(40).

Simple enough but when I replace 127.0.0.1 with my ip address I get nothing ( I turned off the firewall too). The basic topology of my home network consists of a wireless modem (using dsl) and my computer is connected via a wireless usb card. There are about two other active computers on the network. I thought that may have something to do with the connection.

I also wondered how could I modify the code so I can type udp_test:client(40,127.0.0.1). instead and change the client function to accept two arguments in udp_test? I tried simply doing client(N,ip) and changing the function gen_udp:send(Socket, "ip",,) but that came up with a no matching clause error.

-module(udp_test).
-export([start_server/0, client/1]).

start_server() ->
    spawn(fun() -> server(4000) end).

%% The server         
server(Port) ->
    {ok, Socket} = gen_udp:open(Port, [binary]),
    io:format("server opened socket:~p~n",[Socket]),
    loop(Socket).

loop(Socket) ->
    receive
    {udp, Socket, Host, Port, Bin} = Msg ->
        io:format("server received:~p~n",[Msg]),
        N = binary_to_term(Bin),
        Fac = fac(N),
        gen_udp:send(Socket, Host, Port, term_to_binary(Fac)),
        loop(Socket)
    end.

fac(0) -> 1;
fac(N) -> N * fac(N-1).

%% The client

client(N) ->
    {ok, Socket} = gen_udp:open(0, [binary]),
    io:format("client opened socket=~p~n",[Socket]),
    ok = gen_udp:send(Socket, "127.0.0.1", 4000, 
              term_to_binary(N)),
    Value = receive
        {udp, Socket, _, _, Bin} = Msg ->
            io:format("client received:~p~n",[Msg]),
            binary_to_term(Bin)
        after 2000 ->
            0
        end,
    gen_udp:close(Socket),
    Value.

Upvotes: 1

Views: 2801

Answers (1)

Ulf
Ulf

Reputation: 96

write {127,0,0,1} instead of "127.0.0.1".

Ip address

Upvotes: 1

Related Questions