Yah*_*din 5 c tcp packet-capture packet packet-sniffers
我试图解析一个TCP包,然后分配给指向有效负载开始的指针.
我正在使用C,这是我的代码到目前为止:
void dump(const unsigned char *data, int length) { //*data contains the raw packet data
unsigned int i;
static unsigned long pcount = 0;
// Decode Packet Header
struct ether_header *eth_header = (struct ether_header *) data;
printf("\n\n === PACKET %ld HEADER ===\n", pcount);
printf("\nSource MAC: ");
for (i = 0; i < 6; ++i) {
printf("%02x", eth_header->ether_shost[i]); //? Why don't i use nthos here?
if (i < 5) printf(":");
}
unsigned short ethernet_type = ntohs(eth_header->ether_type);
printf("\nType: %hu\n", ethernet_type);
if (ethernet_type == ETHERTYPE_IP) { //IP Header
printf("\n == IP HEADER ==\n");
struct ip *ip_hdr = (struct ip*) data + sizeof(struct ether_header);
unsigned int size_ip = ip_hdr->ip_hl * 4;
printf("\nIP Version: %u", ip_hdr->ip_v); //? Nthos or no nthos
printf("\nHeader Length: %u", ip_hdr->ip_hl); //? Nthos or no nthos
printf("\nTotal Length: %hu", ntohs(ip_hdr->ip_len)); //? Nthos or no nthos
// TCP Header
printf("\n== TCP HEADER ==\n");
struct tcphdr *tcp_hdr = (struct tcphdr*) data + sizeof(struct ether_header) + size_ip;
printf("\n Source Port: %" PRIu16, nthos(tcp_hdr->th_sport));
printf("\n Destination Port: %" PRIu16, nthos(tcp_hdr->th_dport));
printf("\n fin: %" PRIu16, tcp_hdr->fin);
printf("\n urg: %" PRIu16, tcp_hdr->urg);
printf("\n ack_seq: %" PRIu32, ntohl(tcp_hdr->ack_seq));
//Transport payload! i.e. rest of the data
const unsigned char *payload = data + ETH_HLEN + size_ip + sizeof(struct tcphdr) + tcp_hdr->doff;
}
Run Code Online (Sandbox Code Playgroud)
我确定这段代码有错误,因为端口号都很奇怪.没有一个人分配到80.输出的Ip版本也可能非常奇怪(如版本11).我究竟做错了什么?谢谢!
此外,我不确定何时使用nthos,何时不使用.我知道nthos是16位无符号整数,我知道nthol是32位无符号整数,但我知道你并不打算将它们用于那些数据包中的所有内容(例如:tcp_hdr-> fin).为什么某些事情而不是他们?
非常感谢!
编辑:
感谢Art解决了大部分问题.我编辑了我的tcp_hdr和ip_hdr,所以括号现在正确了!
我还有两个问题:
EDIT2
我已经修复了为什么我的有效负载没有正确输出(这是因为我计算的TCP_header大小错误).
虽然我仍然对何时使用nthos感到困惑,但我会将此作为一个单独的问题,因为我认为我在这一篇文章中提出了太多问题!
很可能你的问题在这里:
struct ip *ip_hdr = (struct ip*) data + sizeof(struct ether_header);
struct tcphdr *tcp_hdr = (struct tcphdr*) data + sizeof(struct ether_header) + size_ip;
Run Code Online (Sandbox Code Playgroud)
这样做(struct ip*) data + sizeof(struct ether_header)首先投射数据struct ip *,然后添加sizeof(struct ether_header)到它,这是我们从指针算术知道不会做你希望它做什么.
如果问题仍然不清楚,这是一个简单的程序,应该指向正确的方向:
#include <stdio.h>
struct foo {
int a, b;
};
int
main(int argc, char **argv)
{
char *x = NULL;
printf("%p\n", x);
printf("%p\n", (struct foo *)x + 4);
printf("%p\n", (struct foo *)(x + 4));
return 0;
}
Run Code Online (Sandbox Code Playgroud)