Skip to content

Instantly share code, notes, and snippets.

@seth
Created September 6, 2012 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seth/3659877 to your computer and use it in GitHub Desktop.
Save seth/3659877 to your computer and use it in GitHub Desktop.
Example sending empty binary over a TCP socket
Let's actually see what's going on. Change client to send via this "tunnel":
socat -v TCP4-LISTEN:9898,fork TCP4:localhost:5678
> 2012/09/06 14:05:24.413264 length=5 from=0 to=4
hello
This confirms that sending <<>> is, eventually, a nop in the sense of no data sent over the wire. But it takes a number of function calls to not send anything.
9> spawn(fun() -> tcp1:server() end).
<0.54.0>
10> tcp1:client(<<>>).
ok
S: accepted
This is bogus. What you're seeing is that the socket gets closed by the client that sends nothing and then the empty list which is passed into do_recv is converted to binary and then printed.
S: received: '<<>>'
11>
-module(tcp1).
-compile([export_all]).
server() ->
{ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0},
{active, false}]),
{ok, Sock} = gen_tcp:accept(LSock),
io:format("S: accepted~n"),
{ok, Bin} = do_recv(Sock, []),
io:format("S: received: '~p'~n", [Bin]),
ok = gen_tcp:close(Sock),
Bin.
do_recv(Sock, Bs) ->
case gen_tcp:recv(Sock, 0) of
{ok, B} ->
do_recv(Sock, [Bs, B]);
{error, closed} ->
{ok, list_to_binary(Bs)}
end.
client(Bin) ->
SomeHostInNet = "localhost", % to make it runnable on one machine
{ok, Sock} = gen_tcp:connect(SomeHostInNet, 9898,
[binary, {packet, 0}]),
ok = gen_tcp:send(Sock, Bin),
ok = gen_tcp:close(Sock).
@vinoski
Copy link

vinoski commented Sep 6, 2012

Try changing line 21 from:

{ok, list_to_binary(Bs)}

to:

{ok, list_to_binary([Bs, <<"closed">>])}

and you'll see that all you get is the closed message.

@vinoski
Copy link

vinoski commented Sep 6, 2012

Better yet, change line 19 from:

do_recv(Sock, [Bs, B]);

to:

do_recv(Sock, [Bs, <<B/binary, "XX">>]);

and you won't see any "XX" in your result if you send an empty binary from the client.

You can also watch your localhost interface and port 5678 with wireshark, and if you try to send an empty binary you'll never see a PSH sent but you will if you send actual data.

@seth
Copy link
Author

seth commented Sep 6, 2012

Good suggestions. The bit with socat is a cheap and fast substitute for wireshark. It provides a text dump of anything sent to the socket and you can see that nothing arrives in the empty case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment