C/C ++ network programming issues and Network Programming
1. network programming when you define the struct implementation protocol, you must pay attention to the issue of byte alignment. Otherwise, the sizeof and forced conversion pointers will encounter bugs that are hard to find.
What is byte alignment on Baidu.
1 # pragma pack (1) // byte alignment control! Be very careful! 2 // define an ethernet header 3 typedef struct ehhdr 4 5 {6 7 UCHAR eh_dst [6];/* destination ethernet addrress */8 9 UCHAR eh_src [6]; /* source ethernet addresss */10 11 USHORT eh_type;/* ethernet pachet type */12 13} ETHERHEAD; 14 15 // 28 bytes ARP request/response 16 17 typedef struct arphdr18 19 {20 21 USHORT arp_hrd;/* format of hardware address */22 23 USHORT arp_pro; /* format of protocol address */24 25 UCHAR arp_hln;/* length of hardware address */26 27 UCHAR arp_pln;/* length of protocol address */28 29 USHORT arp_op; /* ARP/RARP operation */30 31 UCHAR arp_sha [6];/* sender hardware address */32 33 ULONG arp_spa; /* sender protocol address */34 35 UCHAR arp_tha [6];/* target hardware address */36 37 ULONG arp_tpa;/* target protocol address */38 39} ARPHEAD; 40 41 # Control of pragma pack () // byte alignment
2. Note the network-byte sequence and local-byte sequence conversion. Use ntohs () and other functions. The following is an example of a winpcap callback function, which is used to check whether the local machine is performing ARP scanning. If you have any suggestions for the code, please point them out.
1 void packet_handler_ARP (u_char * param, const struct pcap_pkthdr * header, const u_char * pkt_data) 2 {3 struct tm * ltime; 4 ltime = new struct tm; 5 char timestr [16]; 6 time_t local_ TV _sec; 7 time_t tTimer = time (0); 8 static unsigned short nNum; 9 10 if (tTimer-g_tStartTimer> SNIFF_TIME) // time sniffing time 11 pcap_breakloop (g_OpenDev); 12 13/* convert the timestamp into a recognizable format */14 local_ TV _sec = header-> ts. TV _sec; 15 localtime_s (ltime, & local_ TV _sec); 16 strftime (timestr, sizeof timestr, "% H: % M: % S", ltime ); 17 18 printf ("% s, %. 6d len: % d \ n ", timestr, header-> ts. TV _usec, header-> len); 19 20 // sniff whether arp21-etherhead * pEtherHead = NULL; 22 pEtherHead = (ETHERHEAD *) pkt_data; 23 if (strncmp (const char *) (pEtherHead-> eh_src), (const char *) (g_aMac), 6) = 0) {// check whether the source address is 24 ARPHEAD * pARPHead = NULL; 25 // printf ("ARP data sent by the local host"); 26 pARPHead = (ARPHEAD *) (pkt_data + sizeof (ETHERHEAD); 27 if (ntohs (pARPHead-> arp_pro) = 0x0800 & // IP28 ntohs (pARPHead-> arp_op) = 0x0001 & // ARP Request29 (ntohl (pARPHead-> arp_tpa) & 0xffff0000) = 0xc0a80000) {// It is the Intranet IP30 nNum ++ of ARP requests; 31 // printf ("count + 1 \ n"); 32 if (nNum> WARN_NUM) {// The count exceeds the threshold value of 33 g_bWarning = true; 34 pcap_breakloop (g_OpenDev ); 35} 36} 37} 38 39 40}