当前位置:文档之家› UDP校验和计算实例

UDP校验和计算实例

UDP校验和的计算实例说明
成都信息工程学院 郑郁正
如下定义一个UDP的以太包。为了方便,只包含两个字节数据0x55,0xaa。
unsigned char udp_et_pkt[] = {
Mac_dest1, Mac_dest2, Mac_dest3, Mac_dest4 ,Mac_dest5, Mac_dest6, //以太网目标地址
Mac_source1, Mac_source2, Mac_source3, Mac_source4, Mac_source5, Mac_source6, //以太网源地址
0x08, 0x00,

//IP 头
0x45, 0x00, IPlenght_h, IPlenght_l,
0x00, 0x00, 0x00, 0x00,
0x80, 0x11, IPchecksum4, IPchecksum5, //0x11为UDP协议
IPsource_1, IPsource_2, IPsource_3, IPsource_4, //源IP地址
IPdestination_1, IPdestination_2, IPdestination_3, IPdestination_4, //目标IP地址

//udp 头
0x04, 0x00, //源端口号
0x04, 0x00, //目标端口号
lenght_h, lenght_l, //(udp头 + 数据)的长度,即8+2
0x00, 0x00, //udp_et_pkt[40] 和 udp_et_pkt[41] //待计算的UDP校验和

//udp 数据
0x55, 0xaa
};

在计算之前要从IP头和UDP头中抽取数据形成UDP伪头:
unsigned char psd[]={
IPsource_1, IPsource_2, IPsource_3, IPsource_4,
IPdestination_1, IPdestination_2, IPdestination_3, IPdestination_4,
0x00,0x11,
lenght_h, lenght_l};

参与UDP校验计算的由三部分组成:udp头,udp数据,udp伪头,如下面所示
unsigned char udp_chksum_data[] = {
//udp 头
0x04, 0x00, //源端口号
0x04, 0x00, //目标端口号
lenght_h, lenght_l, // udp头长度 + udp数据长度 = 8 + 2 //(udp头 + 数据)的长度
0x00, 0x00, //待计算的UDP校验和

//udp 数据
0x55, 0xaa,

//udp 伪头
IPsource_1, IPsource_2, IPsource_3, IPsource_4,
IPdestination_1, IPdestination_2, IPdestination_3, IPdestination_4,
0x00,0x11, //协议,高字节为0x00
lenght_h, lenght_l // udp头长度 + udp数据长度 = 8 + 2
}
计算校验和的程序如下:
uint16 udp_chksum(uint8 *sdata, uint16 len)
{
uint32 acc;

for(acc = 0; len > 1; len -= 2, sdata += 2) acc += (*sdata<<8) + *(sdata+1);
if(len == 1) acc += *sdata<<8;
acc += acc>>16;
return acc;
}
通过下面语语句即可完成UDP的校验计算的填写:
{
uint16 sum = udp_chksum( udp_chksum_data, 8 + 2 + 12 ); //8为udp头长,2为数据长,12为伪头长
sum = ~sum; //取反
udp_et_pkt[40] = sum >> 8; //校验和高8位
udp_et_pkt[41] = sum; //校验和低8位
}

相关主题
文本预览
相关文档 最新文档