我有以下数据包格式:
1B 4B 1B 1B string 2 bytes 1B string
+------+----------+---+--------+---~~--+---------+--------+---~~---+
| type | lifetime | 2 | length | Name | Counter | length | Data |
+------+----------+---+--------+---~~--+---------+--------+---~~---+
typedef struct pkt_data {
u_char pkt_type;
u_int lifetime;
u_char type;
u_char len_name;
u_char name[100];
u_short counter;
u_char len_data;
u_char data[200];
}__attribute__((__packed__)) Data;
下面是构造和解析数据包的代码:
int buildDataPacket(u_int _lifetime, u_char* _name, u_short _counter, u_char* _data, u_char* _dataPacket) {
Data *ndata=NULL;
u_char *ptr;
memset(_dataPacket, 0, 512);
ndata = (Data *) _dataPacket;
ndata->pkt_type = 2;
ndata->lifetime = htonl(_lifetime);
ndata->type = 2;
ndata->len_name = strlen(_name);
ptr = (u_char *)ndata + (3 * sizeof(u_char)) + sizeof(u_int);
strncpy((char *)ptr, (char *)_name, strlen(_name));
u_short counter = htons(_counter);
u_char datalen = strlen(_data);
ptr = ptr + strlen(_name);
memcpy(ptr, &counter, sizeof(u_short));
ptr = ptr + sizeof(u_short);
memcpy(ptr, &datalen, sizeof(u_char));
ptr = ptr + sizeof(u_char);
strncpy((char *)ptr, (char *)_data, strlen(_data));
ptr = ptr + strlen(_data);
return (ptr - (u_char *)_dataPacket);
}
int processDataPacket(u_char* _dataPacket, u_short _pktLen)
{
if (!_dataPacket || !_pktLen) {
return -1;
}
Data *dataPkt;
dataPkt = (Data *)_dataPacket;
printf("Lifetime: %d\n", ntohl(dataPkt->lifetime));
printf("Name: %s\n", dataPkt->name);
printf("Counter: %d\n", dataPkt->counter);
printf("Data: %s\n", dataPkt->data);
return 0;
}
当我在wireshark中嗅探数据包时,发现数据包的构造是按照格式来的。但是“counter”和“len_data”的值是零,即使我相应地设置了它们。此外,当我收到数据包时,完整的数据包不会存储在缓冲区中。
rval=recvfrom(inet_sock, buf, BUFLEN-1, MSG_DONTWAIT, (struct sockaddr *) &dest_sin, &socklen);
buf[rval]=0;
fprintf(stderr, "Received: %d (%d) bytes containing %s", rval, strlen(buf), buf);
“rval”返回正确的总字节数,但“buf”在“name”之后终止。strlen(buf) 仅返回数据包的长度,直到名称为止。所以“数据”在 processDataPacket 中是空的。请指导我如何构造和解析这个数据包。