[关闭]
@xunuo 2017-11-20T20:11:01.000000Z 字数 1399 阅读 1152

tcp校验和验证


网络数据包分析

怎么计算比较容易看懂的博客:
http://www.cnblogs.com/RodYang/p/3265515.html

具体有哪些字段比较容易看懂的博客:
http://blog.csdn.net/zhangskd/article/details/11770647

代码比较容易懂的博客:
http://blog.csdn.net/u013005025/article/details/52870857


-psd_header

  1. struct psd_header{
  2. unsigned long saddr; //源地址
  3. unsigned long daddr; //目的地址
  4. char mbz;//置空
  5. char ptcl; //协议类型
  6. unsigned short tcpl; //TCP长度
  7. };
  1. /*计算tcp校验和*/
  2. u_short get_checksum(u_char* pudp_pkt, int pkt_len)
  3. {
  4. /*pudp_pkt表示整个数据包的数据(packet_content),pkt_len为除以太网首部的长度。*/
  5. ip_header *ip_hdr = (ip_header*)(pudp_pkt + sizeof(ether_header));
  6. tcphdr *tcp_hdr = (tcphdr*)((char*)ip_hdr + sizeof(ip_header));
  7. psd_header psdheader;
  8. /*tcp伪头部中的len: =tcp包头长度+数据长度(数据包总长度-ethernet包头长度-ip包头长度);*/
  9. u_short tcp_len = pkt_len - sizeof(ip_header);
  10. psdheader.ptcl = ip_hdr->ip_protocol;
  11. psdheader.daddr = ip_hdr->daddr;
  12. psdheader.saddr = ip_hdr->saddr;
  13. psdheader.mbz = 0x00;
  14. psdheader.tcpl = htons(tcp_len);
  15. tcp_hdr->check = 0x0000;//预置tcp校验和为0;
  16. int psdlen = sizeof(psd_header);
  17. int buf_size = tcp_len + psdlen;// 亚包头 + udp包头 + 数据部分的总长度
  18. if (pkt_len < buf_size)
  19. return 0;
  20. u_char* buffer = (u_char*)malloc(buf_size);
  21. memset(buffer, 0x00, buf_size);
  22. memcpy(buffer, (char*)&psdheader, psdlen);
  23. memcpy(buffer + psdlen, (char*)tcp_hdr, tcp_len);
  24. unsigned char* ptr_data = buffer;
  25. u_long tmp = 0;
  26. u_long sum = 0;
  27. for (int i = 0; i<buf_size; i += 2)
  28. {
  29. tmp += (u_char)ptr_data[i] << 8;
  30. tmp += (u_char)ptr_data[i + 1];
  31. sum += tmp;
  32. tmp = 0;
  33. }
  34. u_short lWord = sum & 0x0000FFFF;
  35. u_short hWord = sum >> 16;
  36. u_short checksum = lWord + hWord;
  37. checksum = ~checksum;
  38. return checksum;
  39. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注