Skip to content

Instantly share code, notes, and snippets.

@seth
Created September 6, 2012 19:48
Show Gist options
  • 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).
@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