1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| static int handle_event(void *ctx, void *data, size_t data_sz) { if (data_sz < 20) { fprintf(stderr, "Received incomplete TCP header\n"); return 0; }
struct tcphdr { uint16_t source; uint16_t dest; uint32_t seq; uint32_t ack_seq; uint16_t res1:4, doff:4, fin:1, syn:1, rst:1, psh:1, ack:1, urg:1, ece:1, cwr:1; uint16_t window; uint16_t check; uint16_t urg_ptr; } __attribute__((packed));
if (data_sz < sizeof(struct tcphdr)) { fprintf(stderr, "Data size (%zu) less than TCP header size\n", data_sz); return 0; }
struct tcphdr *tcp = (struct tcphdr *)data;
uint16_t source_port = ntohs(tcp->source); uint16_t dest_port = ntohs(tcp->dest); uint32_t seq = ntohl(tcp->seq); uint32_t ack_seq = ntohl(tcp->ack_seq); uint16_t window = ntohs(tcp->window);
uint8_t flags = 0; flags |= (tcp->fin) ? 0x01 : 0x00; flags |= (tcp->syn) ? 0x02 : 0x00; flags |= (tcp->rst) ? 0x04 : 0x00; flags |= (tcp->psh) ? 0x08 : 0x00; flags |= (tcp->ack) ? 0x10 : 0x00; flags |= (tcp->urg) ? 0x20 : 0x00; flags |= (tcp->ece) ? 0x40 : 0x00; flags |= (tcp->cwr) ? 0x80 : 0x00;
printf("Captured TCP Header:\n"); printf(" Source Port: %u\n", source_port); printf(" Destination Port: %u\n", dest_port); printf(" Sequence Number: %u\n", seq); printf(" Acknowledgment Number: %u\n", ack_seq); printf(" Data Offset: %u\n", tcp->doff); printf(" Flags: 0x%02x\n", flags); printf(" Window Size: %u\n", window); printf("\n");
return 0; }
|