1

我试图在 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;
4

0 回答 0