Turn simple C program into server using netcat

我与影子孤独终老i 提交于 2020-01-22 21:23:29

问题


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:


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



来源:https://stackoverflow.com/questions/22185228/turn-simple-c-program-into-server-using-netcat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!