【问题标题】:Connect to the unix-socket using bash使用 bash 连接到 unix-socket
【发布时间】:2021-02-20 11:48:25
【问题描述】:

我在 cpp 中有一个简单的服务器,它只监听一个套接字并打印接收到的数据。

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
    int sock, listener;
    struct sockaddr_in addr;
    char buf[1024];
    int bytes_read;

    listener = socket(AF_INET, SOCK_STREAM, 0);
    if(listener < 0)
    {
        perror("socket");
        exit(1);
    }
    
    addr.sin_family = AF_INET;
    addr.sin_port = htons(3210);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("bind");
        exit(2);
    }

    listen(listener, 1);
    
    while(1)
    {
        sock = accept(listener, NULL, NULL);
        if(sock < 0)
        {
            perror("accept");
            exit(3);
        }

        while(1)
        {
            bytes_read = recv(sock, buf, 1024, 0);
            if(bytes_read <= 0) break;
            printf(buf);
            send(sock, buf, bytes_read, 0);
        }
    
        close(sock);
    }
    
    return 0;
}

我需要使用 bash 连接到服务器的套接字(不使用其他一些实用程序)并发送一些消息。

我试着写一个脚本。看起来是这样的:

 exec 4</dev/tcp/0.0.0.0/3210
 echo -ne "Message" >&4

但它不起作用。

ss -t -a 命令的输出

State      Recv-Q Send-Q Local Address:Port          Peer Address:Port  Process 

LISTEN     0      1            0.0.0.0:3210               0.0.0.0:*    

那么,我应该怎么做才能使用“清除” bash 连接到服务器的套接字并在服务器上发送消息??

【问题讨论】:

  • 0.0.0.0 表示它正在侦听所有接口,但您不能使用0.0.0.0 作为连接的IP 地址。使用127.0.0.1 连接到本地主机。

标签: c++ c linux bash sockets


【解决方案1】:

您的服务器在 localhost 上运行,因此您应该使用 127.0.0.1

那么对于测试,我更喜欢使用netcattelnet 例如:telnet 127.0.0.1 3210 或者对于简单的消息发送者,您可以使用:echo message &gt; /dev/tcp/127.0.0.1/3210

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2019-07-02
    相关资源
    最近更新 更多