概述
- 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计算校验和的全部内容,希望文章能够帮你解决UDP计算校验和所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复