Created
October 6, 2020 21:50
-
-
Save casperin/e7595b7fffdf4497e544403087057c23 to your computer and use it in GitHub Desktop.
Erlang TCP Spy -- a little broken
This file contains 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(tcpspy). | |
-export([start/3, stop/1, start_spy/3, listener/3, handler/2]). | |
start(Port, ServerHost, ServerPort) -> | |
spawn(?MODULE, start_spy, [Port, ServerHost, ServerPort]). | |
stop(Spy) -> | |
exit(Spy, shutdown), | |
ok. | |
start_spy(Port, ServerHost, ServerPort) -> | |
{ok, Socket} = gen_tcp:listen(Port, [binary, {active, true}, {reuseaddr, true}]), | |
io:format("Listening on port ~p~n", [Port]), | |
listener(Socket, ServerHost, ServerPort). | |
listener(Socket, ServerHost, ServerPort) -> | |
{ok, Client} = gen_tcp:accept(Socket), | |
{ok, Server} = gen_tcp:connect(ServerHost, ServerPort, []), | |
Handler = spawn(fun () -> handler(Client, Server) end), | |
gen_tcp:controlling_process(Client, Handler), | |
gen_tcp:controlling_process(Server, Handler), | |
listener(Socket, ServerHost, ServerPort). | |
handler(Client, Server) -> | |
receive | |
{tcp, Client, Data} -> | |
io:format("->~n~s", [Data]), | |
gen_tcp:send(Server, Data), | |
handler(Client, Server); | |
{tcp, Server, Data} -> | |
io:format("<-~n~s", [Data]), | |
gen_tcp:send(Client, Data), | |
handler(Client, Server); | |
{tcp_closed, Client} -> | |
gen_tcp:close(Server); | |
{tcp_closed, Server} -> | |
gen_tcp:close(Client) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment