我在写socketraw程序时,遇到了一个问题,就是tcp包头部的校验和老是出错,我用的是书上的那个checksum函数,我的代码简单的就是下面的,我把HttpBuf这个里面的作为tcp的data,然后计算校验和,可是就是不对,而不要这个HttpBuf的时候,倒是计算没有问题,到底是怎样的问题呢?char HttpBuf[]="\r\n<html>\r\nfsafsaf\r\n</html>\r\n";//填充IP首部
ipHeader.h_lenver=(4<<4 | sizeof(ipHeader)/sizeof(unsigned long));
// ipHeader.tos=0;
ipHeader.total_len=htons(sizeof(ipHeader)+sizeof(tcpHeader));
ipHeader.ident=1;
ipHeader.frag_and_flags=0;
ipHeader.ttl=128;
ipHeader.proto=IPPROTO_TCP;
ipHeader.checksum=0;
ipHeader.sourceIP=inet_addr("218.57.142.211");
ipHeader.destIP=inet_addr("218.57.137.84"); //填充TCP首部
tcpHeader.th_dport=htons(80);
tcpHeader.th_sport=htons(1234); //源端口号
tcpHeader.th_seq=htonl(0x12345678);
tcpHeader.th_ack=htonl(0x11111111);
tcpHeader.th_lenres=(sizeof(tcpHeader)/4<<4|0);
tcpHeader.th_flag=24; 
tcpHeader.th_win=htons(512);
tcpHeader.th_urp=0;
tcpHeader.th_sum=0; psdHeader.saddr=ipHeader.sourceIP;
psdHeader.daddr=ipHeader.destIP;
psdHeader.mbz=0;
psdHeader.ptcl=IPPROTO_TCP;
psdHeader.tcpl=htons(sizeof(tcpHeader)); //计算校验和
memcpy(szSendBuf, &psdHeader, sizeof(psdHeader));
memcpy(szSendBuf+sizeof(psdHeader), &tcpHeader, sizeof(tcpHeader));
memcpy(szSendBuf+sizeof(psdHeader)+sizeof(tcpHeader), HttpBuf, sizeof(HttpBuf));
tcpHeader.th_sum=checksum((USHORT *)szSendBuf,sizeof(psdHeader)+sizeof(tcpHeader)); memcpy(szSendBuf, &ipHeader, sizeof(ipHeader));
memcpy(szSendBuf+sizeof(ipHeader), &tcpHeader, sizeof(tcpHeader));
memset(szSendBuf+sizeof(ipHeader)+sizeof(tcpHeader), 0, 4);
ipHeader.checksum=checksum((USHORT *)szSendBuf, sizeof(ipHeader)+sizeof(tcpHeader)); memcpy(szSendBuf, &ipHeader, sizeof(ipHeader)); memcpy(szSendBuf+sizeof(ipHeader)+sizeof(tcpHeader),HttpBuf,100); rect=sendto(sock, szSendBuf, sizeof(ipHeader)+sizeof(tcpHeader)+sizeof(HttpBuf),0, (struct sockaddr*)&addr_in, sizeof(addr_in));
if (rect==SOCKET_ERROR)
{
printf("send error!:%d\n",WSAGetLastError());
return false;
}
else
printf("send ok!\n");