简体   繁体   中英

Redirect STDIN to socket and socket to STDOUT

I am trying to develop a simple command-line client to the server. After I connect to the server and setup everything correctly I want to redirect STDIN to the socket connected to the server and the same socket to STDOUT . I want to achieve behavior similar to the of nc tool.

The most simple solution would be use select() and use read() / write() to pass data from STDIN to the socket and from the socket to STDOUT .

Is there any other simpler way to somehow connect socket to to the STDIN / STDOUT? I thought about using dup2() system call. However, I am not sure how to make it work.

Thanks.

On Linux you can use splice(2) to move data between file descriptors at the kernel level. Though, you would still have to use select(2) (or equivalent) to handle the two directions in parallel or alternatively use two threads.

Another possibility is to do the protocol handshaking in your program and, once the socket is ready, exec a program as socat to perform the data forwarding.

For instance, call dup2 to copy the socket into file descriptor 3, unset its close-on-exec flag and then exec socat STDIO FD:3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM