Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn simple C program into server using netcat

Tags:

c

unix

stdio

netcat

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.

like image 870
Peter Avatar asked Mar 04 '14 23:03

Peter


1 Answers

There's a high chance stdout is not line-buffered when writing to a non-terminal. Do an fflush(stdout) just after the printf.

like image 185
cnicutar Avatar answered Oct 01 '22 02:10

cnicutar