public IP4Header(ByteBuffer buffer) { try { byte versionAndIHL = (byte)buffer.Get(); this.version = (byte)(versionAndIHL >> 4); this.IHL = (byte)(versionAndIHL & 0x0F); this.headerLength = this.IHL << 2; this.typeOfService = BitUtils.GetUnsignedByte((byte)buffer.Get()); this.totalLength = BitUtils.GetUnsignedShort(buffer.Short); this.identificationAndFlagsAndFragmentOffset = buffer.Int; this.TTL = BitUtils.GetUnsignedByte((byte)buffer.Get()); this.protocolNum = BitUtils.GetUnsignedByte((byte)buffer.Get()); this.protocol = (TransportProtocol)protocolNum; this.headerChecksum = BitUtils.GetUnsignedShort(buffer.Short); byte[] addressBytes = new byte[4]; buffer.Get(addressBytes, 0, 4); this.sourceAddress = InetAddress.GetByAddress(addressBytes); buffer.Get(addressBytes, 0, 4); this.destinationAddress = InetAddress.GetByAddress(addressBytes); //this.optionsAndPadding = buffer.getInt(); } catch { throw new UnknownHostException(); } }
private void updateTCPChecksum(int payloadSize) { int sum = 0; int tcpLength = TCP_HEADER_SIZE + payloadSize; // Calculate pseudo-header checksum ByteBuffer buffer = ByteBuffer.Wrap(ip4Header.sourceAddress.GetAddress()); sum = BitUtils.GetUnsignedShort(buffer.Short) + BitUtils.GetUnsignedShort(buffer.Short); buffer = ByteBuffer.Wrap(ip4Header.destinationAddress.GetAddress()); sum += BitUtils.GetUnsignedShort(buffer.Short) + BitUtils.GetUnsignedShort(buffer.Short); sum += ((int)IP4Header.TransportProtocol.TCP) + tcpLength; buffer = backingBuffer.Duplicate(); // Clear previous checksum buffer.PutShort(IP4_HEADER_SIZE + 16, (short)0); // Calculate TCP segment checksum buffer.Position(IP4_HEADER_SIZE); while (tcpLength > 1) { sum += BitUtils.GetUnsignedShort(buffer.Short); tcpLength -= 2; } if (tcpLength > 0) { sum += BitUtils.GetUnsignedByte((byte)buffer.Get()) << 8; } while (sum >> 16 > 0) { sum = (sum & 0xFFFF) + (sum >> 16); } sum = ~sum; tcpHeader.checksum = sum; backingBuffer.PutShort(IP4_HEADER_SIZE + 16, (short)sum); }