Skip to content

Instantly share code, notes, and snippets.

@rnewson
Created January 4, 2014 16:02
Show Gist options
  • Save rnewson/8256811 to your computer and use it in GitHub Desktop.
Save rnewson/8256811 to your computer and use it in GitHub Desktop.
trivial SOCKS5 handling in Erlang.
#!/usr/bin/env escript
-define(VERSION, 16#05).
-define(CONNECT, 16#01).
-define(NO_AUTH, 16#00).
-define(RESERVED, 16#00).
-define(ATYP_IPV4, 16#01).
-define(ATYP_DOMAINNAME, 16#03).
-define(SUCCEEDED, 16#00).
main([Url]) ->
{ok, Socket} = gen_tcp:connect("localhost", 9050, [binary, {active, false}]),
% SOCKS5 with no authentication
ok = gen_tcp:send(Socket, <<?VERSION, 1, ?NO_AUTH>>),
{ok, <<?VERSION, ?NO_AUTH>>} = gen_tcp:recv(Socket, 0),
% Send HTTP request via SOCKS proxy
BinUrl = list_to_binary(Url),
Size = byte_size(BinUrl),
ok = gen_tcp:send(Socket,
<<?VERSION, ?CONNECT, ?RESERVED, ?ATYP_DOMAINNAME, Size, BinUrl/binary, 80:16>>),
{ok, Packet} = gen_tcp:recv(Socket, 0),
<<?VERSION, ?SUCCEEDED, ?RESERVED, ?ATYP_IPV4, Addr:32, Port:16>> = Packet,
erlang:display({negotiated, Addr, Port}),
% Make the request.
Request = <<"GET / HTTP/1.0\r\n\r\n">>,
ok = gen_tcp:send(Socket, Request),
{ok, Response} = gen_tcp:recv(Socket, 0),
io:format("received via Tor: ~p", [Response]),
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment