当前位置: 技术问答>linux和unix
关于接收端对TCP报文校验和的处理
来源: 互联网 发布时间:2015-08-05
本文导语: 我用以下的函数对接收到的TCP报文校验和进行处理 struct pseudo_tcphdr { struct in_addr ip_src; struct in_addr ip_dst; u_char zero; u_char protocol; u_short len; }; u_short tr_cksum (u_short * addr, int...
我用以下的函数对接收到的TCP报文校验和进行处理
struct pseudo_tcphdr
{
struct in_addr ip_src;
struct in_addr ip_dst;
u_char zero;
u_char protocol;
u_short len;
};
u_short tr_cksum (u_short * addr, int len, struct in_addr sip, struct in_addr dip, u_char protocol)
{
register int nleft = len;
register int sum = 0;
register u_short * w;
u_short answer = 0;
struct pseudo_tcphdr pseudo_hdr;
pseudo_hdr.ip_src.s_addr = sip.s_addr;
pseudo_hdr.ip_dst.s_addr = dip.s_addr;
pseudo_hdr.zero = 0;
pseudo_hdr.protocol = protocol;
pseudo_hdr.len = htons (len);
w = (u_short *) &pseudo_hdr;
sum += *w++; sum += *w++; sum += *w++;
sum += *w++; sum += *w++; sum += *w++;
w = addr;
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
*(u_char *)(&answer) = *(u_char *)w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0XFFFF);
sum += sum >>16;
answer = ~sum;
return answer;
}
....
while (1)
{
if ((cc = recvfrom (receiversd, buf, buflen, 0, (struct sockaddr *) &sock, &socklen)) > 0)
{
cc -= ethhdrlen;
pip = (struct ip *) (buf + ethhdrlen);
iphdrlen = pip->ip_hl
struct pseudo_tcphdr
{
struct in_addr ip_src;
struct in_addr ip_dst;
u_char zero;
u_char protocol;
u_short len;
};
u_short tr_cksum (u_short * addr, int len, struct in_addr sip, struct in_addr dip, u_char protocol)
{
register int nleft = len;
register int sum = 0;
register u_short * w;
u_short answer = 0;
struct pseudo_tcphdr pseudo_hdr;
pseudo_hdr.ip_src.s_addr = sip.s_addr;
pseudo_hdr.ip_dst.s_addr = dip.s_addr;
pseudo_hdr.zero = 0;
pseudo_hdr.protocol = protocol;
pseudo_hdr.len = htons (len);
w = (u_short *) &pseudo_hdr;
sum += *w++; sum += *w++; sum += *w++;
sum += *w++; sum += *w++; sum += *w++;
w = addr;
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
*(u_char *)(&answer) = *(u_char *)w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0XFFFF);
sum += sum >>16;
answer = ~sum;
return answer;
}
....
while (1)
{
if ((cc = recvfrom (receiversd, buf, buflen, 0, (struct sockaddr *) &sock, &socklen)) > 0)
{
cc -= ethhdrlen;
pip = (struct ip *) (buf + ethhdrlen);
iphdrlen = pip->ip_hl