使用一行 telnet 语句时,C 套接字读取输出空字符串

标签 c sockets telnet

我在一行中使用 telnet 和 echo 通过 TCP 套接字读取客户端输入时遇到问题。它仅在我在“正常”telnet session 中输入消息时才有效:

客户端控制台

devbox cehrig # telnet 127.0.0.1 50231
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Test Message
Connection closed by foreign host.
devbox cehrig # echo "One Liner" | telnet 127.0.0.1 50231
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Connection closed by foreign host.
devbox cehrig # 

服务器控制台

Mon Apr  6 16:36:41 2015: Accepting connections...
Mon Apr  6 16:36:45 2015: Inbound connection from  127.0.0.1
Client msg: Test Message
Mon Apr  6 16:36:48 2015: Accepting connections...
Mon Apr  6 16:44:06 2015: Inbound connection from  127.0.0.1
Client msg: 
Mon Apr  6 16:44:06 2015: Accepting connections...

尝试使用 echo ""发送数据时“Client msg”始终为空 |远程登录....

这是我用来从客户端套接字读取的函数:

void read_socket(int idntef, 
         config_t * cfg)
{
    int n;
    char * _buf = (char *) malloc(512*sizeof(char));
    char * _cor = (char *) malloc(512*sizeof(char));
    char * _out = _cor;

    bzero(_buf, 512);
    bzero(_cor, 512);


    if((n = read(idntef, _buf, 511)) < 0) {
        _print(stderr, "messages.socketreadfail", cfg, 1);
        _exit(0);
    }

    int x = 0;
    while(*_buf != '\n' && x++ <= 512) {
        *_cor++ = *_buf++;
    }

    printf("Client msg: %s\n", _out);
    fflush(stdout);
    shutdown(idntef, 2);
}

sbd 是否有提示给我,这里需要改进什么?

最佳答案

不保证数据会在一个 block 中发送。您需要循环读取,直到找到“\n”或达到缓冲区限制。

类似于:

size_t size=0;
do {
    if((n = read(idntef, _buf+size, 512-size)) < 0) {
        _print(stderr, "messages.socketreadfail", cfg, 1);
        _exit(0);
    }
    size += n;
} while(strchr(_buf, '\n') == NULL && size < 512);

关于使用一行 telnet 语句时,C 套接字读取输出空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29474609/

相关文章:

c++ - 无法让 sigaction 工作

c++ - C/C++ Linux下可登录telnet服务器的telnet库

http - 当我尝试使用 HTTP 协议(protocol)发出请求时,为什么会收到 Bad Request 响应?

没有malloc的C编程

c - 如何将整数指针设置为数字,并使其表现为非指针整数?

c - 二进制 0000 到 FFFF 使用 C

Java:套接字还是 RMI?

java - 新的Socket挂起应用程序

linux - Telnet 使用用户名和密码登录邮件服务器

c - 多个 '++' 在变量和指针中工作