我在星期天用 libpcap 来了解数据包嗅探,我已经到了可以读取数据包和元数据的地步。当我通过嗅探一些数据包来检查我的代码时,我发现我一定有一个错误。
当我从我父亲那里嗅探网页时:http://www.telpho.de,我得到了整个服务器的响应。从 200 OK 开始直到 ... 但是在每个数据包上,开头有 4 个字节不是 ASCII。在下面的代码中,当我将 for 循环更改为 (i = 0) 时,也会打印 4 个字节。当我将其保留在 (i = 4) 时,有效负载将从收到的第一个 ASCII 字符完美显示。
我现在的问题是,我计算 data_offset 错误吗?有没有我没有设置的标志?我忘记计算 tcp 选项了吗?
我还认为这可能与填充有关。TCP 标准说 TCP 标头长度应该是 32 的倍数。但是 32 - 20 = 12 .. 所以这是 3 个字节的差异。
例如,计算是这样的吗?
TCP_HDR_SIZE = 32
sizeof(struct tcphdr) = 20
tcp->doff = 8
sizeof(struct tcphdr) + tcp->doff = 28
TCP_HDR_SIZE - 28 = 4 <--- the 4 bytes i am looking for??? Maybe options?
这是代码:
void handle_packet_ip(const struct pcap_pkthdr *header, const u_char* data) {
struct ip *ip;
struct tcphdr *tcp;
int ip_len;
int data_offset;
int payload_len;
int i;
unsigned char* payload;
ip = (struct ip*)(data + sizeof(struct ether_header));
ip_len = (ip->ip_hl & 0x0f) * 4;
tcp = (struct tcphdr*)(data + sizeof(struct ether_header) + ip_len);
printf("sizeof(ip): %d\n", sizeof(struct ip));
printf("ip_len: %d\n", ip_len);
printf("sizeof(ether_header): %d\n", sizeof(struct ether_header));
printf("sizeof(tcp): %d\n", sizeof(struct tcphdr));
data_offset = sizeof(struct ether_header) + ip_len + sizeof(struct tcphdr) + tcp->doff;
payload_len = header->len - data_offset;
payload = (unsigned char*)(data + data_offset);
printf("IP PACKET\n");
printf("\tlen: %u\n", ntohs(ip->ip_len));
printf("\tsrc: %s\n", inet_ntoa(ip->ip_src));
printf("\tdst: %s\n", inet_ntoa(ip->ip_dst));
printf("\thl: %d\n", (ip->ip_hl & 0x0f));
printf("READ TCP\n");
printf("\tsrc port: %u\n", ntohs(tcp->source));
printf("\tdst port: %u\n", ntohs(tcp->dest));
printf("\tdata_offset: %d\n", data_offset);
printf("\tdoff: %d-%d\n", tcp->doff, ntohs(tcp->doff));
printf("\tpayload len: %d\n", payload_len);
printf("\tFLAGS\n");
printf("\t\tFIN: %i\n", tcp->fin);
printf("\t\tSYN: %i\n", tcp->syn);
printf("\t\tACK: %i\n", tcp->ack);
printf("PAYLOAD: \n");
**for (i = 4; i < payload_len; ++i) {**
printf("%c", payload[i]);
}
printf("\n");
printf("\n");
printf("END OF PAYLOAD\n");
}
输出:
Grabbed Packet:
Length: 74
Capture Length: 74
sizeof(ip): 20
ip_len: 20
sizeof(ether_header): 14
sizeof(tcp): 20
IP PACKET
len: 60
src: 80.237.132.106
dst: 192.168.0.17
hl: 5
READ TCP
src port: 80
dst port: 57662
data_offset: 62 **this should be 64 ??**
doff: 8
payload len: 10
FLAGS
FIN: 0
SYN: 1
ACK: 1