当前位置: 动力学知识库 > 问答 > 编程问答 >

C Socket, Add header before data stream

问题描述:

I'm sending bytes through sockets and that works fine. Now in terms of transfer files, I need to send file size before sending actual data. So I come up a idea that send file size as a header before file data.

For example, if file data is "1234", then socket will send 4 bytes of its length (which is 4) before "1234" and there will be 8 bytes sending through socket. First 4 bytes contains data length, and the rest of bytes are actual data.

I can convert int into bytes (i.e. char array) by:

bytes[0] = (n >> 24) & 0xFF;

bytes[1] = (n >> 16) & 0xFF;

bytes[2] = (n >> 8) & 0xFF;

bytes[3] = n & 0xFF;

The problem is I can't add this 4 bytes before actual data:

char *data = [Actual data of file];

char *buffer = malloc(4 + strlen(data));

strcpy(buffer, bytes);

strcat(buffer, data);

The result of this is that bytes[] are gone, and buffer has exactly same data as data

Can anyone help me with this?

网友答案:

You don't need to prepend the length bytes to your data buffer. Use a separate buffer. Then you can send() the length buffer before you send() the data buffer. Even better, you can store the data length in a 32-bit int or uint32_t, using htonl() to arrange the bytes in network byte order, and then send() that directly without copying it to its own buffer. This becomes easier to manage if you wrap your send logic in a function, eg:

void sendData(void *data, uint32_t datalen)
{
    uint32_t len = htonl(datalen);
    send(socket, &len, sizeof(len), 0);
    send(socket, data, datalen, 0);
}

char *data = [Actual data of file];
uint32_t datalen = [Actual length of file];

sendData(data, datalen);
网友答案:

Ok, I'm assuming that you know what you are doing with data, and that it is a nul-terminated string, and that you don't want to send the terminator (because you don't allocate space for it in your buffer). What you want could be done as follows:

size_t len = strlen(data);
char *buffer = malloc(4 + len);
memcpy(buffer, bytes, 4);
memcpy(buffer + 4, data, len);

Note that your bytes are NOT a string, therefore you do NOT want to use string functions like strcpy or strcat on them. memcpy(dst, src, len) just copies exactly len bytes from src to dst, not caring about the actual contents such as nul-terminators.

分享给朋友:
您可能感兴趣的文章:
随机阅读: