使用 recv 充满垃圾的缓冲区

buffer filled with trash using recv

目标接收到正确的字节数,但接收到的字符串是垃圾。

辅助功能:

ssize_t send_all(int socket, const void *buffer, size_t length, int flags) {
    ssize_t n;
    const char *p = buffer;
    while (length > 0)
    {
        n = send(socket, p, length, flags);
        if (n <= 0) break;
        p += n;
        length -= n;
    }
    return (n <= 0) ? -1 : 0;   
}

这是我的发件人:

p_status_t aviso_gestion_tema(struct sockaddr_in id, char* tema, int tema_name_length, tipo_msg_intermediario precedente) {

//...

int cd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(connect(cd, (struct sockaddr*) &id, sizeof(id)) == -1) {
    #ifdef DEBUG_ERR
        fprintf(stderr, "connect: %s\n", strerror(errno));
    #endif 
    op_result = CALLBACK_TRANSM_ERROR;
}
else if(send(cd, &tipo, 1, 0) == -1) { op_result = CALLBACK_TRANSM_ERROR; }
else if(send_all(cd, &tema, tema_name_length, 0) == -1) { op_result = CALLBACK_TRANSM_ERROR; }

#ifdef DEBUG_MSG
    fprintf(stderr, "aviso-gestion-gema (%d bytes): %s\n", tema_name_length, tema);
#endif

close(cd);

这是我在接收器上所做的简化:

int cd;
char tipo_msg;
struct sockaddr_in client_ain;
socklen_t c_ain_size;
char buff[BUFFER_SIZE];
ssize_t buff_readed_aux;
unsigned int tema_name_length;

c_ain_size = sizeof(client_ain);
cd = accept(socket_recepcion, (struct sockaddr*)&client_ain, &c_ain_size);
if(cd == -1) {...}

tipo_msg = (char) 0;
if(recv(cd, &tipo_msg, 1, 0) == -1) {...}

buff_readed_aux = recv(cd, &buff, sizeof(buff), 0)));
printf("\n-> Recibida alta tema %s\n", buff);

如果我检查内存 buff_readed_aux 值是正确的,但缓冲区充满了垃圾。

我在照片上得到的值示例:

Client: aviso-gestion-gema (7 bytes): nombre1.  
Server: Recibida alta tema P�`

Client: aviso-gestion-gema (5 bytes): nom#2
Server: Recibida alta tema ��`

我不明白发生了什么,我曾尝试使用 'bzero' 来初始化缓冲区,但没有成功。我已经用 wireshark 确认消息没有从服务器正确发送。

Tema 分配在哈希 table 中,如下所示:

tema_name_length = strlen(utstring_body(readed));
char* allocated = malloc(tema_name_length+1); // 1+ for nul termination
strcpy(allocated, utstring_body(readed));
// store allocated in the hash-table
buff_readed_aux = recv(cd, &buff, sizeof(buff), 0)));
printf("\n-> Recibida alta tema %s\n", buff);

您如何期望此 printf 知道要打印多少个字符?魔术?

尝试,例如:

if (buff_readed_aux > 0)
{
    printf("\n-> Recibida alta tema ");
    for (int i = 0; i < buff_readed_aux; ++i) putchar(buff[i]);
    printf("\n");
}

另外:

 else if(send_all(cd, &tema, tema_name_length, 0) == -1) { op_result = CALLBACK_TRANSM_ERROR; }

#ifdef DEBUG_MSG
    fprintf(stderr, "aviso-gestion-gema (%d bytes): %s\n", tema_name_length, tema);
#endif

如果 tema 包含您要发送的地址(如 fprintf 所建议的),为什么要传递 地址 temasend_all?您应该传递 send_all 您要发送的地址,而不是包含您要发送的地址的地址!