Cast struct c / c ++

0

I'm looking at a network sniffer code and I do not understand the following lines:

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

How do these cast with struct work?

//////////////////////////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;
 }
    
asked by anonymous 26.10.2015 / 20:47

1 answer

1

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

struct sniff_ethernet represents the Ethernet header that has 6 bytes for the destination address, 6 bytes for the source address, and 2 bytes for EtherType . So the first 16 bytes of the array of packet characters are destined to this struct .

The struct sniff_ip represents the IP header is taking the information that is in array packet and entering struct for better manipulation.

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

packet + SIZE_ETHERNET , means that you are getting the address of packet , and summing it with the size of the Ethernet header, that is, you will be assigning this struct only the header information IP .

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

    
27.10.2015 / 01:16