目标接收到正确的字节数,但接收到的字符串是垃圾。
辅助功能:
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 在哈希表中分配,如下所示:
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
所示),为什么要传递 tema
的地址至send_all
?你应该通过send_all
您要发送的内容的地址,而不是保存您要发送的内容的地址!
关于c - 使用 recv 填充垃圾的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751850/