UDP计算校验和

//the checksum static unsigned short checksum(unsigned short *pwbuffer,uint32_t size) { unsigned long cksum=0; while(size > 1){ cksum+=*pwbuffer++; size-=sizeof(uint16_t); } if(size){ cksum+=*(uint8_t*)pwbuffer; } cksum=(cksum>>16)+(cksum&0xffff); cksum+=(cksum >> 16); return (unsigned short)(~cksum); } static unsigned int inline udp_checksum(unsigned long saddr, unsigned long daddr, unsigned short *buffer, int size) { unsigned char rawBuf[1024]; struct pseudo_hdr { struct in_addr src; struct in_addr dst; uint8_t mbz; uint8_t proto; uint16_t len; } __attribute__((__packed__)); unsigned long sum = 0; struct pseudo_hdr *ph; int ph_len = sizeof(struct pseudo_hdr); ph = (struct pseudo_hdr *)rawBuf; ph->src.s_addr = saddr; ph->dst.s_addr = daddr; ph->mbz = 0; ph->proto = IPPROTO_UDP; ph->len = htons(size); //这里的长度为udp header + payload 的总和 //buffer = udpheader + payload, size = sizeof(udpheader + payload) memcpy(rawBuf + ph_len, buffer, size); //ph_len + size 是虚假头长+UDP长+payload长。来计算checksum sum = checksum((unsigned short*)rawBuf,ph_len+size); return(sum); }

如上代码是计算udp的checksum函数! 如果无法确定自己的计算是否正确,可以用wireshar或ethreal抓包工具看看是否正确.

 

参考链接:http://www.linuxforums.org/forum/programming-scripting/114077-udp-checksum-problem.html

你可能感兴趣的:(struct,header,buffer,工具,DST)