Created
September 6, 2012 19:48
-
-
Save seth/3659877 to your computer and use it in GitHub Desktop.
Example sending empty binary over a TCP socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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). |
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
Better yet, change line 19 from:
to:
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.