简体   繁体   English

可以使用strncpy复制tcp流导致故障吗?

[英]Can using strncpy to copy tcp stream cause malfunction?

I am making a simple proxy server. 我正在制作一个简单的代理服务器。 And I have a very hard time with parsing response. 我在解析响应方面非常困难。

// Case 1
do {
    memset(buffer, 0, BUFSIZE);
    con = read(sockfd, buffer, BUFSIZE);
    write(client, buffer, con);
} while(con);

// Case 2
do {
    memset(buffer, 0, BUFSIZE);
    con = read(sockfd, buffer, BUFSIZE);
    size += con;
    cachebuf = (char*)realloc(cachebuf, size);
    strncpy(cachebuf+(size-con), buffer, con);
} while(con);
write(client, cachebuf, size);

These two samples receive a TCP stream from the end server, and forward it to browser. 这两个示例从终端服务器接收TCP流,并将其转发到浏览器。 The only difference is that first one forwards the stream as soon as it receives it, and second one saves the stream in the cachebuf pointer and sends as a whole(which it the case I want to use) 唯一的区别是第一个接收流后立即转发流,第二个将流保存在cachebuf指针中并作为整体发送(我想要使用它)

It seems same, and both works fine when it receives a HTML file. 它看起来一样,并且在收到HTML文件时都可以正常工作。 However, the second one can not send images. 但是,第二个无法发送图像。 Why does this happen? 为什么会这样?

You can't use strncpy (and friends) to copy binary data. 您不能使用strncpy (和朋友)来复制二进制数据。 This function copies bytes until it encounters nul-terminator ( '\\0' ). 此函数复制字节,直到遇到nul-terminator( '\\0' )。 Binary data, in particularly, images, have a lot of those characters in them, and string functions will not copy it completely. 二进制数据,特别是图像,其中包含许多字符,字符串函数不会完全复制它。

To copy binary data, you can use memcpy or std::copy . 要复制二进制数据,可以使用memcpystd::copy

On a side note, your memset before read is completely unnecessary and just contributes to global warming without doing anything useful. 另外,在read之前,你的memset完全没有必要,只是在没有做任何有用的事情的情况下有助于全球变暖。

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

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