使用recv填充垃圾的缓冲区

时间:2016-04-20 18:09:45

标签: c sockets tcp client-server 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);

这简化了我在reciver上所做的事情:

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 ��`

我不明白发生了什么事,我试图使用&#39; bzero&#39;没有运气地初始化缓冲区。我已经通过wireshark确认消息没有从服务器正确发送。

Tema在这样的哈希表中分配:

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

1 个答案:

答案 0 :(得分:1)

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建议的那样),为什么要将tema地址传递给{ {1}}?你应该传递send_all你要发送的地址,而不是那个包含你要发送的地址的地址!