I am trying to parse a tcp package and then assign a pointer to the beginning of the payload.
I am using C and this is my code:
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! ie rest of the data const unsigned char *payload = data + ETH_HLEN + size_ip + sizeof(struct tcphdr) + tcp_hdr->doff; }
I am sure that there are errors in this code, because the port numbers are all strange. None of them assign 80. The output version of Ip can also be very strange (for example, version 11). What am I doing wrong? Thanks!
Also, I'm not sure when to use nthos, and when not. I know that nthos is for a 16-bit unsigned integer, and I know that nthol is for 32-bit unsigned integers, but I know that you should not use them for everything that is in these packages (for example: tcp_hdr-> fin). Why are some things, not them?
MANY THANKS!
EDIT:
Thanks to Art for fixing most of the problems. I edited my tcp_hdr and ip_hdr, so the brackets are now correct!
I still have 2 problems:
- The first 10 bytes of the payload have strange characters (so I think I did not assign the payload correctly).
- I still don't know when to use nthos / nthol. I know that u_int16_t is ntohs and u_int32_t is ntohl. But what about things that signed int or unisgned short int. For example, I did not use ntohs or nthol for ip_v to make it work. Why not? Is "ip_hdr-> ip_hl" nthol? etc...
EDIT2
I found out why my payload was not output correctly (this is because I did not correctly calculate the TCP_header size).
Although I'm still confused when to use nthos, I would pose this as a separate question since I think I asked too many questions in this 1 post!
When to use ntohs and ntohl in C?