C#中的IP头校验和功能

时间:2014-03-11 10:21:59

标签: c# packet

我有Packet byte[]

byte[] arr = {
    17, 34, 51, 68, 85, 102, 0, 20, 34, 24, 129, 17, 8, 0, 69, 0, 0, 95,
    88, 117, 0, 0, 128, 17, 136, 254, 10, 61, 50, 135, 172, 49, 112, 37,
    9, 129, 6, 110, 0, 75, 244, 143, 4, 1, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 107, 105, 110, 111, 8, 6, 10, 61 ,50, 135,
    9, 6, 255, 255, 255, 255, 31, 8, 55, 55, 55, 55, 55, 55, 40, 6, 0, 0, 0,
    1, 44, 6, 53, 53, 53, 53, 30, 9, 55, 53, 50, 50, 53, 53, 53 };

我想要做的是尝试更改我的Packet IP地址,以便找到计算Checksum的{​​{3}}函数,我只想了解我需要向此发送哪些参数功能(我对网络知识不多,我开始学习)

private Packet ChangePacketIp(Packet packet, IpV4Address oldIpAddress, IpV4Address newIpAddress)
{
    // calculate the checksum
    ushort checksum = ComputeHeaderIpChecksum(packet.Buffer, 0, packet.Buffer.Length);
    // create header from checksum and data
    byte[] header = new byte[packet.Buffer.Length + 2];
    Array.Copy(packet.Buffer, 0, header, 2, packet.Buffer.Length);
    header[0] = (byte)(checksum >> 8); // high byte first
    header[1] = (byte)(checksum & 0xff); // low byte 2n)d

    try
    {
        EthernetLayer ethernet = (EthernetLayer)packet.Ethernet.ExtractLayer();
        IpV4Layer ipV4Layer = (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer();
        DateTime packetTimestamp = packet.Timestamp;

        if (packet.Ethernet.IpV4.Source == oldIpAddress)
        {
            ipV4Layer.Source = newIpAddress;
            ipV4Layer.HeaderChecksum = null;
        }
        else if (packet.Ethernet.IpV4.Destination == oldIpAddress)
        {
            ipV4Layer.CurrentDestination = newIpAddress;
            ipV4Layer.HeaderChecksum = null;
        }

        if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
        {
            TcpLayer tcpLayer = (TcpLayer)packet.Ethernet.IpV4.Tcp.ExtractLayer();
            tcpLayer.Checksum = null;
            ILayer payload = packet.Ethernet.IpV4.Tcp.Payload.ExtractLayer();
            return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, tcpLayer, payload);
        }
        else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
        {
            UdpLayer udpLayer = (UdpLayer)packet.Ethernet.IpV4.Udp.ExtractLayer();
            udpLayer.Checksum = null;
            ILayer payload = packet.Ethernet.IpV4.Udp.Payload.ExtractLayer();
            return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, udpLayer, payload);
        }
        else
        {
            return null;
        }
    }
    catch (Exception)
    {
        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

那将是

// calculate the checksum
ushort checksum = XYClassName.ComputeHeaderIpChecksum(arr, 0, arr.Length);

// create header from checksum and data
byte[] header = new byte[arr.Length + 2];
Array.Copy(arr, 0, header, 2, arr.Length);
header[0] = checksum >> 8; // high byte first
header[1] = checksum & 0xff; // low byte 2nd