Coder Perfect

In Bash, how can I make a simple socket server?

Problem

Is there a method to fast bind to a TCP port/IP address and have everything printed to STDOUT? I have a simple debugging solution that writes to 127.0.0.1:4444, and I’d like to be able to use bash to bind a port and report everything that comes across. Is there a simple way to accomplish this?

Asked by Naftuli Kay

Solution #1

$ nc -k -l 4444 > filename.out

see nc(1)

Answered by Nikolai Fetissov

Solution #2

Simply because you requested how to accomplish it in bash, despite the fact that the netcat response is perfectly valid:

  $ exec 3<>/dev/tcp/127.0.0.1/4444
  $ cat <&3

Answered by Diego Torres Milano

Solution #3

That’s exactly how you expected it to work:

 nc -k -l 4444 |bash

and then you

echo "ls" >/dev/tcp/127.0.0.1/4444

Then you’ll see the output of bash’s listing.

[An Important Security Notice] Of course, leaving anything like this running on your computer opens the door to all kinds of attacks because orders may be issued from any user account on any machine in your network. This has no security (authentication, identification) and sends all communicated commands over the network unencrypted, making it exceedingly easy to abuse.

Answered by luk

Solution #4

Adding a ncat answer that @Freedom Ben mentioned:

ncat -k -l 127.0.0.1 4444

and a description of the choices from man ncat:

-k, --keep-open            Accept multiple connections in listen mode
-l, --listen               Bind and listen for incoming connections

Answered by Kilokahn

Post is based on https://stackoverflow.com/questions/4739196/simple-socket-server-in-bash