一个补语算法n C.

时间:2018-04-14 18:08:11

标签: c udp checksum ones-complement

我试图在C中计算UDP数据报的校验和。 为了计算UDP校验和,您需要创建一个伪标头,将其作为数据报的前缀,然后计算伪标头和数据报的一个补码和的16位补码。

为了计算一个人的补充总和,我想也许这样可行:

~((n + k) - 1) // Where n and k are unsigned 16 bit integers.

这会给我计算n和k之间的补充加法的结果吗?

谢谢。

编辑:

这里是UDP校验和的代码:

   uint16_t compute_udp_checksum(IP *ip, UDP *u,
        void *data, int data_len)
   {

    PSEUDO_HDR *ps = NULL;
    void *buffer = NULL;
    uint16_t sum = 0, *arr = NULL;
    int size = UDP_SIZE + PS_SIZE + data_len;

    ps = create_pseudo_hdr(ip, u); // Create the pseudo-header.
    if (!ps) // If the pseudo header is not allocated, exit.
            return 0;

    if (size % 2) // If the size is not a multiple of 2,
            size += 1; // then add 1 to do so.

    buffer = malloc(size); // Allocate memory to the buffer.
    if (!buffer) // If the memory is not allocated, exit.
     {
            perror("malloc");
            free(ps);
            return 0;
     }

    memset(buffer, 0, size); // Clear the memory.
    memcpy(buffer, ps, PS_SIZE); // Copy the pseudo header.
    memcpy(buffer + PS_SIZE, u, UDP_SIZE); // Then, copy the UDP header.
    memcpy(buffer + PS_SIZE + UDP_SIZE, data, data_len); // Finally, copy the data.

    arr = (uint16_t *) buffer;
    int i = 0;
    while (i < size) // Loop through the buffer.
     {
            sum = ones_complement_add(sum, ones_complement_add(arr[i], arr[i + 1])); // Perform a one's complement addition.
            i += 2; // Go to the next pair.
     }

    /* Deallocate memory to the pseudo header and buffer. */
    free(ps);
    free(buffer);

    sum = ~sum; // Take the one's complement of the sum.
    return sum;

0 个答案:

没有答案