1

I'm trying to setup a simple TCP server in bash that can listen for request, process the data received and then send a response to the client.
Is there any way to do this properly using netcat ?

edit - what i've have already tried :

  • Piping the output of the server to a bash script :
    nc -kl 4444 | bash pipe.sh
    Then, in pipe.sh, read the answer. But there is some downside to this : sometimes read is acting weirdly and do not get the full output, and I couldn't find a way to send a response to the client.
  • Something more complete looking like this, however it causes some problems as it's meant to be interactive and wait for user input, so sometimes the server answers 2 times or simply doesn't answer anything.
2
  • Welcome to Stack Overflow! Please update your question to show what you have already tried in a minimal, complete, and verifiable example and add sample input and expected output. For further information, please see how to ask good questions, and take the tour of the site :) Commented Mar 8, 2018 at 18:08
  • Bash might be buffering stuff through that pipe..maybe write your own server... Commented Oct 24, 2018 at 16:40

1 Answer 1

1

Look at this example script, it uses bash input/output redirection to establish a socket connection for the purpose of sending SMTP mail. I'm sure you can re-purpose the concept for what you're doing, with the advantage that it's all bash built-ins (it does not require netcat).

The core logic is:

exec 3<>/dev/tcp/$MAILSERVER/$PORT 
echo -en "HELO mail.email.com\r\n"  >&3 
echo -en "MAIL FROM:$MAILFROM\r\n" >&3
echo -en "RCPT TO:$MAILTO\r\n" >&3
echo -en "DATA\r\n" >&3
echo -en "Subject: $SUBJECT\r\n\r\n" >&3
echo -en "$DATA\r\n" >&3
echo -en ".\r\n" >&3
echo -en "QUIT\r\n" >&3
cat <&3

The exec 3<>/dev/tcp/$MAILSERVER/$PORT part creates the >&3 and <&3 redirectors; anything you output to >&3 gets sent to the remote port, and cat <&3 types to the console all data received from the remote server in response.

Sign up to request clarification or add additional context in comments.

1 Comment

As far as I understand, I cannot listen on a port using /dev/tcp/ (as I saw here), so the problem of sending response to a client and processing data isn't solved. However, I think this could work well as a client. Thanks for your time !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.