代码之家  ›  专栏  ›  技术社区  ›  Mehan Alavi

TCP Socket-打印字符串中所有不在C中的字符不起作用

  •  2
  • Mehan Alavi  · 技术社区  · 11 月前

    我有一个 recv 我用来接收套接字的函数(这里是一个HTTP GET请求)。 我只是想删除请求的“\n”,这样我就可以更轻松地工作了。

    代码:

    void receiveHTTP(int clientSockfd, char *buff, size_t __n, int __flags)
    {
        int bytes = recv(clientSockfd, buff, __n, __flags);
        printf("%s",buff);
        for (int i = 0; i < strlen(buff); i++)
        {
            if (buff[i] != '\n'){
                printf("%c", buff[i]);
            }
        }
    }
    

    输出:

    GET /1 HTTP/1.1
    user-agent: got (https://github.com/sindresorhus/got)
    accept-encoding: gzip, deflate, br
    cookie: PHPSESSID=37f65v1f9dcbmq3nbvqvev6bf4
    Host: localhost:8080
    Connection: close
    

    这确实很酷,但它的无新版本还没有印刷出来。原因是什么?

    提前感谢。

    2 回复  |  直到 11 月前
        1
  •  3
  •   Remy Lebeau    11 月前

    您完全忽略了的返回值 recv() ,告诉你具体有多少 char 它真的放进去了吗 buff .

    这个 %s 指定者 printf() 需要一个以null结尾的字符串,但是 浅黄色 不能保证为空终止。您应该传递以下返回值 recv() 输出函数 因此,它知道可以安全打印多少个字符。

    同样,你也不需要 strlen() 因为你已经知道里面有多少个字符 浅黄色 .

    您正在打印以下内容 浅黄色 两次,这是你真正想要的吗?

    最后,HTTP使用 \r\n 用于断线,而不仅仅是 \n 本身。

    请尝试以下操作:

    void receiveHTTP(int clientSockfd, char *buff, size_t __n, int __flags)
    {
        int bytes = recv(clientSockfd, buff, __n, __flags);
        if (bytes <= 0) return;
    
        // prints the whole thing...
        printf("%.*s",bytes,buff);
        // or: fwrite(buff, bytes, 1, stdout);
        // or: write(STDOUT_FILENO, buff, bytes);
    
        // prints everything ignoring line breaks...
        for (int i = 0; i < bytes; ++i)
        {
            if (buff[i] != '\r' && buff[i] != '\n'){
                printf("%c", buff[i]);
            }
        }
    }
    

    此外,请记住,此函数只是从套接字读取任意字节,它实际上并没有解释HTTP协议的结构。HTTP可以发送ASCII文本和二进制数据的混合,这段代码没有区分。

        2
  •  0
  •   Remy Lebeau    11 月前

    正如@AndreasWenze所指出的,HTTP换行符实际上是 \r\n \n .

    更新代码:

    void receiveHTTP(int clientSockfd, char *buff, size_t __n, int __flags)
    {
        int bytes = recv(clientSockfd, buff, __n, __flags);
        printf("%s",buff);
        for (int i = 0; i < bytes; i++)
        {
            if (buff[i+1] != '\n' && buff[i] != '\n' ){
                printf("%c", buff[i]);
            }
        }
        printf("\n");
    }
    

    输出:

    GET /1 HTTP/1.1
    user-agent: got (https://github.com/sindresorhus/got)
    accept-encoding: gzip, deflate, br
    cookie: PHPSESSID=37f65v1f9dcbmq3nbvqvev6bf4
    Host: localhost:8080
    Connection: close
    
    GET /1 HTTP/1.1user-agent: got (https://github.com/sindresorhus/got)accept-encoding: gzip, deflate, brcookie: PHPSESSID=37f65v1f9dcbmq3nbvqvev6bf4Host: localhost:8080Connection: close
    

    这是正确的。