Bash – How to set a script to execute when a port receives a message

bashdaemonnetworkingshell-script

I'm wondering how to get a shell script to listen in on a certain port (maybe using netcat?). Hopefully so that when a message is sent to that port, the script records the message and then runs a function.

Example:

  1. Computer 1 has the script running in the background, the script opened port 1234 to incoming traffic

  2. Computer 2 sends message "hello world" to port 1234 of computer 1

  3. Script on Computer 1 records the message "hello world" to a variable $MESSAGE

  4. Script runs function now that variable $MESSAGE has been set

How do I go about doning this?

Best Answer

Should be possible with socat.

Write such a script "getmsg.sh" to receive one message via stdin:

#!/bin/bash
read MESSAGE
echo "PID: $$"
echo "$MESSAGE"

Then run this socat command to invoke our script for each tcp connection on port 7777:

socat -u tcp-l:7777,fork system:./getmsg.sh

Send a test message from another shell:

echo "message 1" | netcat localhost 7777
Related Question