5

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
shooly
  • 53
  • 3
  • 1
    Bash itself does not have any socket or network capability. You have to use other programs to handle the network bits. One such program could be e.g. [netcat](http://nc110.sourceforge.net/). You might also want to read e.g. [this question and its answers](http://stackoverflow.com/q/16640054/440558). – Some programmer dude Apr 25 '14 at 08:02
  • `wall` may do what you want too. – Deanna Apr 25 '14 at 08:05
  • @Mat I don't want to connect with PHP server - PHP is my client, and Bash - my server. – shooly Apr 25 '14 at 08:16

3 Answers3

2

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>.

Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
2

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.

perreal
  • 94,503
  • 21
  • 155
  • 181
2

There is a project on GIT which implements a HTTP web server fully written in bash;

https://github.com/avleen/bashttpd

Gio
  • 3,242
  • 1
  • 25
  • 53