[erlang-questions] TCP Kernel bug/feature
Tom Samplonius
tom@REDACTED
Fri May 18 04:39:56 CEST 2007
----- "Martin Carlson" <martin@REDACTED> wrote:
> Hi all,
>
> Came across a strange Linux kernel bug/feature this morning while
> testing
> a TCP application we've written.
>
> The following code captures the behavior.
>
> server(Ip, Port) ->
> {ok, Socket} = gen_tcp:listen(Port, [{ip, Ip}, {reuseaddr, true},
> {packet, 4}, binary]),
> {ok, Client} = gen_tcp:accept(Socket),
> gen_tcp:close(Socket),
> Client.
>
>
> client(Ip, Port) ->
> case gen_tcp:connect(Ip, Port, [{packet, 4}, binary]) of
> {ok, Client} ->
> Client;
> {error, econnrefused} ->
> client(Ip, Port);
> {error, Reason} ->
> erlang:error(Reason)
> end.
>
>
> node1() ->
> server({127,0,0,1}, 12345),
> halt().
>
>
> node2() ->
> client("127.0.0.1", 12345),
> io:format("Connection lost~n"),
> client("127.0.0.1", 12345).
>
> When running node1() on one Erlang node and node2 on another
> this creates a socket connected to itself. One can capture the socket
> and
> pass data forth and back.
>
> netstat gives the following result:
> tcp 0 0 127.0.0.1:12345 127.0.0.1:12345
> ESTABLISHED
>
> This however only seem to work on Suse 9.3 with a stock kernel and
> has
> probably been fixed in newer versions of the kernel.
>
> uname say:
> 2.6.11.4-20a-smp #1 SMP Wed Mar 23 21:52:37 UTC 2005 i686 i686 i386
> GNU/Linux
I think this is way it is supposed to work. A socket is a unique pair of source and destination ports. You run a server on 12345, and then connect from 12345 to 12345. So that is a legal socket. This should work this way on most OSes.
Normally when you establish a client connection, you don't special the port to establish the socket from. You let the OS use the next available number from some magical pool of ports. You should have a really good reason to establish a connection from a specific port.
>
> --
> Martin Carlson
> Erlang Training & Consulting
> http://www.erlang-consulting.com
>
Tom
More information about the erlang-questions
mailing list