bWilliamson
bWilliamson

Reputation: 196

Sending Raw Tcp Packet Using NetCat to Erlang Server

I am trying to create a TCP Server which will store incoming TCP Packets as binary, for a Key/Value Store. I already have an Erlang client which can send TCP packets to my Erlang Server, however for the sake of completeness, I want to allow the user to send TCP packets from a command line using clients such as NetCat. The user would adhere to a spec of how to format the data in the TCP Packet such that the Server will be able to understand it. For Example

$ nc localhost 8091
add:key:testKey
Key Saved!
add:value:testValue
Value Saved!
get:key:testKey
Value: testValue

The user interacts with the server by using the add:key/value: and get:key:. What is after that should be taken literally and passed to the server. Meaning a situation like this could be possible, if the user so wanted to.

$ nc localhost 8091
add:key:{"Foo","Bar"}
Key Saved!
add:value:["ferwe",324,{2,"this is a value"}]
Value Saved!
get:key:{"Foo","Bar"}
Value: ["ferwe",324,{2,"this is a value"}]

However, this doesn't seem possible to do as what actually happens is as follows...

I will pre-fill the erlang key/value store (using ETS) using my erlang client with a key of {"Foo","Bar"} and a value of ["ferwe",324,{2,"this is a value"}]. A tuple and list respectively (in this example) as this key/value store has to be able to accommodate ANY erlang compliant data type.

So in the example, currently there is 1 element in the ETS table:

Key Value
{"Foo","Bar"} ["ferwe",324,{2,"this is a value"}]

I then want to retrieve that entry using NetCat by giving the Key, so I type in NetCat...

$ nc localhost 8091
get:key:{"Foo","Bar"}

My Erlang Server, receives this as <<"{\"Foo\",\"Bar\"}\n">> My Erlang Server is set up to receive binary which is not an issue.

My question is therefore, can NetCat be used to send unencoded Packets which doesn't escape the quote marks. Such that my Server is able to receive the Key and just <<"{"Foo","Bar"}">>

Thank you.

Upvotes: 1

Views: 612

Answers (1)

legoscia
legoscia

Reputation: 41568

My question is therefore, can NetCat be used to send unencoded Packets which doesn't escape the quote marks.

Yes, netcat sends exactly what you give it, so in this case it sends get:key:{"Foo","Bar"} without escaping the quote marks.

Such that my Server is able to receive the Key and just <<"{"Foo","Bar"}">>

<<"{"Foo","Bar"}">> is not a syntactically correct Erlang term. Do you want to get the tuple {"Foo","Bar"} instead, in order to look it up in the ETS table? You can do it by parsing the binary:

Bin = <<"{\"Foo\",\"Bar\"}\n">>,
%% need to add a dot at the end for erl_parse
{ok, Tokens, _} = erl_scan:string(binary_to_list(Bin) ++ "."),
{ok, Term} = erl_parse:parse_term(Tokens),
ets:lookup(my_table, Term).

Upvotes: 2

Related Questions