// pData 指向 ICMP 头部 public void RecalcChecksum(IntPtr pData, IP_HEADER ip_hdr) { //Int16 org_chk_sum = m_nCheckSum; int icmp_hdr_size = Marshal.SizeOf(typeof(ICMP_HEADER)); int size_without_ip_hdr = ip_hdr.GetIPPacketLength() - ip_hdr.GetIPHeaderLength(); Byte[] icmp_chk = new Byte[size_without_ip_hdr]; m_nCheckSum = 0; GCHandle gch_icmp = GCHandle.Alloc(this, GCHandleType.Pinned); Marshal.Copy(gch_icmp.AddrOfPinnedObject(), icmp_chk, 0, icmp_hdr_size); int data_size = size_without_ip_hdr - icmp_hdr_size; Marshal.Copy(pData + icmp_hdr_size, icmp_chk, icmp_hdr_size, data_size); Int16 chk_sum = CalcChecksum(icmp_chk); //System.Diagnostics.Debug.Assert(chk_sum == org_chk_sum); //m_nCheckSum = org_chk_sum; m_nCheckSum = chk_sum; }
// pData 指向 UDP 头部 public void RecalcChecksum(IntPtr pData, IP_HEADER ip_hdr) { //Int16 org_chk_sum = m_nCheckSum; int udp_hdr_size = Marshal.SizeOf(typeof(UDP_HEADER)); int ip_psd_size = Marshal.SizeOf(typeof(TCP_UDP_PSEUDO_HEADER)); int size_without_ip_hdr = ip_hdr.GetIPPacketLength() - ip_hdr.GetIPHeaderLength(); Byte[] udp_chk = new Byte[ip_psd_size + size_without_ip_hdr]; TCP_UDP_PSEUDO_HEADER ip_psd_hdr = new TCP_UDP_PSEUDO_HEADER(); ip_psd_hdr.m_nSrcIP = ip_hdr.GetIPSrcIP(); ip_psd_hdr.m_nDstIP = ip_hdr.GetIPDstIP(); ip_psd_hdr.m_nZero = 0; ip_psd_hdr.m_nProtocol = (Byte)ProtocolType.Udp; ip_psd_hdr.m_nIPLength = (UInt16)IPAddress.HostToNetworkOrder((Int16)size_without_ip_hdr); GCHandle gch_psd = GCHandle.Alloc(ip_psd_hdr, GCHandleType.Pinned); Marshal.Copy(gch_psd.AddrOfPinnedObject(), udp_chk, 0, ip_psd_size); m_nCheckSum = 0; GCHandle gch_udp = GCHandle.Alloc(this, GCHandleType.Pinned); Marshal.Copy(gch_udp.AddrOfPinnedObject(), udp_chk, ip_psd_size, udp_hdr_size); int data_size = size_without_ip_hdr - udp_hdr_size; Marshal.Copy(pData + udp_hdr_size, udp_chk, ip_psd_size + udp_hdr_size, data_size); Int16 chk_sum = CalcChecksum(udp_chk); //System.Diagnostics.Debug.Assert(chk_sum == org_chk_sum); //m_nCheckSum = org_chk_sum; m_nCheckSum = chk_sum; }