One cool feature of netcat
is how it can turn any command line program into a server. For example, on Unix systems we can make a simple date server by passing the date
binary to netcat
so that it's stdout
is sent through the socket:
netcat -l -p 2020 -e date
Then we can invoke this service from another machine by simply issuing the command:
netcat <ip-address> 2020
Even a shell could be connected (/bin/sh
), although I know this is highly unrecommended and has big security implications.
Similarly, I tried to make my own simple C program that both reads and writes from stdin
and stdout
:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
char buffer[20];
printf("Please enter your name:\n");
fgets(buffer, 20, stdin);
printf("Hello there, %s\n", buffer);
return 0;
}
However, when I invoke the service from another terminal, there is no initial greeting; in fact the greeting is only printed after sending some information. For example:
user@computer:~$ netcat localhost 2020
User
Please enter your name:
Hello there, User
What do I need to do so that my greeting will be sent through the socket initially, then wait for input, then send the final message (just like I am invoking the binary directly)?
I know there may be better (and possibly more secure) approaches to implement such a system, but I am curious about the features of netcat
, and why this does not work.
There's a high chance stdout
is not line-buffered when writing to a non-terminal. Do an fflush(stdout)
just after the printf
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With