5

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.

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

You can also use dprintf() which does not bufferize.
@Phibonacci Stellar suggestion if you have a file descriptor.
Thanks for your help guys, this really pointed me in the right direction. I just found another solution that works well. Buffering can also be disabled by calling setbuf, for example: setbuf(stdout, NULL);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.