简体   繁体   English

将STDIN重定向到套接字,并将套接字重定向到STDOUT

[英]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 . 连接到服务器并正确设置所有内容后,我想将STDIN重定向到连接到服务器的套接字,并将同一套接字重定向到STDOUT I want to achieve behavior similar to the of nc tool. 我想要实现类似于nc工具的行为。

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 . 最简单的解决方案是使用select()read() / write()将数据从STDIN传递到套接字,再从套接字传递到STDOUT

Is there any other simpler way to somehow connect socket to to the STDIN / STDOUT? 还有其他更简单的方法可以将套接字连接到STDIN / STDOUT? I thought about using dup2() system call. 我考虑过使用dup2()系统调用。 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. 在Linux上,您可以使用splice(2)在内核级别的文​​件描述符之间移动数据。 Though, you would still have to use select(2) (or equivalent) to handle the two directions in parallel or alternatively use two threads. 但是,您仍然必须使用select(2) (或等效方法)并行处理两个方向,或者使用两个线程。

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. 另一种可能性是在程序中进行协议握手,一旦套接字准备好,就以socat身份执行程序以执行数据转发。

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 . 例如,调用dup2将套接字复制到文件描述符3中,取消设置其close-on-exec标志,然后执行exec socat STDIO FD:3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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