Is there any way to program a server in bash?
Basically I want be able to connect to a bash server from a PHP client and send messages that will be displayed in console.
Is there any way to program a server in bash?
Basically I want be able to connect to a bash server from a PHP client and send messages that will be displayed in console.
The bad news first
Unfortunately, there seems to be no hope to do this in pure Bash.
Even doing a
exec 3<> /dev/tcp/<ip>/<port>
does not work, because these special files are implemented on top on connect() instead of bind(). This is apparent if we look at the source.
In Bash 4.2, for example, the function _netopen4() (or _netopen6() for IPv6) reads as follows (lib/sh/netopen.c):
s = socket(AF_INET, (typ == 't') ? SOCK_STREAM : SOCK_DGRAM, 0);
if (s < 0)
{
sys_error ("socket");
return (-1);
}
if (connect (s, (struct sockaddr *)&sin, sizeof (sin)) < 0)
{
e = errno;
sys_error("connect");
close(s);
errno = e;
return (-1);
}
But
It is possible to use a command line tool such as nc. E.g.,
nc -l <port>
will listen for incoming connections on localhost:<port>.
Create a process that reads from a socket, executes the data via shell, and prints back the response. Possible with the following script, which listens on port 9213:
ncat -l -kp 9213 | while read line; do
out=$($line)
# or echo $line
echo $out
done
If all you want is to display the data, ncat -l -p 9213 is sufficient though.
There is a project on GIT which implements a HTTP web server fully written in bash;