Soody Soody - 6 months ago 21
Bash Question

Shell - calling function with nc -c

This is my Server-Code for now.
I just want to get Data from a Client, analyze it and send my answer.
Is there a way to call my function managedata() in nc? My Code, obviously doesn't work.

server.sh:

managedata()
{
echo $1
#do something with data
return $1
}

listen()
{
echo "Server listening.."
nc -l -p 1234 -c '$(read i && managedata $i && echo $?)'
}

#MAIN
while true;
do
listen
done


Client.sh:

send()
{
echo $1 | nc $ip $port -o 0
}

#
register()
{
read -p "Login: " usrname
echo -n "Password: "
read -s password | shasum > password

#Schleife zum encrypten des Passworts
#Count = n -> Leslie Lamport Alogrithmus
n=5
count=$n
while [ $count -ge 2 ]
do
password="$(cat password | shasum)"
((count--))
done

password=`cat password`
echo
echo $password

data="reg-$usrname-$n-$password"

send $data
}

#
log()
{
echo "..."
}

#
menue()
{
echo "====== Lab: Shell Programming (BS) ======"
echo " r Register"
echo " l Login"
echo " q Quit"
echo

read -p "your choice: " check

case "$check" in
r) register;;
l) log;;
q) exit;;
esac

}


#MAIN
ip=$1
port=$2

while true
do
menue
done


bash -x server.sh:

+ true
+ listen
+ echo 'Server listening..'
Server listening..
+ nc -l -p 1234 -c '$(read i && managedata $i && echo $?)'
sh: 1: managedata: not found
+ true
+ listen
+ echo 'Server listening..'
Server listening..
+ nc -l -p 1234 -c '$(read i && managedata $i && echo $?)'

Answer

Yep you should "tell" bash to treat managedata as command or function that can be executed. BTW, you need to use $() to execute whole expression not only managedata:

nc -l -p 1234 -c $(read i && managedata $i && echo $?)

Also bash can't return strings, only integer error codes, so return $1 won't work if it's not integer in range of 0 - 255.

Replace to return 0

Comments