Cast struct c/c++

Asked

Viewed 111 times

0

Guys I’m seeing a code of a network Sniffer and I’m not understanding the following lines :

ethernet = (struct sniff_ethernet*)(packet);
ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);

how do these cast with struct?

//////////////////////////função
got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{

 static int count = 1;                   

 /* declare pointers to packet headers */
 const struct sniff_ethernet *ethernet;  
 const struct sniff_ip *ip;              
 const struct sniff_tcp *tcp;            
 const char *payload;                  

 int size_ip;
 int size_tcp;
 int size_payload;

 printf("\nPacket number %d:\n", count);
 count++;


 ethernet = (struct sniff_ethernet*)(packet); ////////

 ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);//////////
 size_ip = IP_HL(ip)*4;
 if (size_ip < 20) {
  printf("   * Invalid IP header length: %u bytes\n", size_ip);
  return;
 }


 printf("       From: %s\n", inet_ntoa(ip->ip_src));
 printf("         To: %s\n", inet_ntoa(ip->ip_dst));


 switch(ip->ip_p) {
  case IPPROTO_TCP:
   printf("   Protocol: TCP\n");
   break;
  case IPPROTO_UDP:
   printf("   Protocol: UDP\n");
   return;
  case IPPROTO_ICMP:
   printf("   Protocol: ICMP\n");
   return;
  case IPPROTO_IP:
   printf("   Protocol: IP\n");
   return;
  default:
   printf("   Protocol: unknown\n");
   return;
 }
  • The Casts has no reason to be in the code presented. When making an assignment to a variable of a different but compatible type value the compiler makes an automatic conversation. The presence of the cast does not help or help before the opposite.

1 answer

1

The function got_packet gets the argument cont u_char* packet, which is a array of characters that contain the bytes of the received package.

To struct sniff_ethernet represents the Ethernet header that has 6 bytes for the target address, 6 bytes for the source address and 2 bytes for Ethertype. Then the first 16 bytes of array character packet are intended for that struct.

To struct sniff_ip represents the header IP in turn, is taking the information that are in the array packet and inserting into the struct for better handling.

ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);

packet + SIZE_ETHERNET, means you’re getting the address of packet, and adding to the size of the Ethernet header, ie will be assigning to this struct only the header information IP.

Thus, the first bytes of the array packet are in the struct sniff_ethernet and the next in the struct sniff_ip, and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.