libicmp/tests/utils/test_checksum.c
lohhiiccc 2e509336c7 feat(utils): add ICMP checksum and time utilities with tests
- Added `icmp_checksum`.
 - Added `icmp_get_time`.
 - Created unit tests for checksum and time.
 - Set `-D_POSIX_C_SOURCE=199309L` in CPPFLAGS for clock_gettime support.
2026-01-24 22:00:24 +01:00

58 lines
1.9 KiB
C

#include <criterion/criterion.h>
#include <stdint.h>
#include "internal/icmp_utils.h"
/* Test 1: Simple ICMP Echo Request header (8 bytes, even length) */
Test(checksum, echo_request_header)
{
/* ICMP Echo Request: type=8, code=0, checksum=0, id=0x1234, seq=0x0001 */
uint8_t packet[] = {
0x08, 0x00, 0x00, 0x00, /* type, code, checksum (zeroed) */
0x12, 0x34, 0x00, 0x01 /* id=0x1234, seq=0x0001 */
};
uint16_t result = icmp_checksum(packet, sizeof(packet));
/* Expected checksum calculated manually (network byte order):
* Words: 0x0800, 0x0000, 0x1234, 0x0001
* Sum: 0x0800 + 0x0000 + 0x1234 + 0x0001 = 0x1A35
* Checksum: ~0x1A35 = 0xE5CA */
cr_assert_eq(result, 0xE5CA,
"Expected checksum 0xE5CA, got 0x%04X", result);
}
/* Test 2: Odd length packet (9 bytes) */
Test(checksum, odd_length)
{
/* ICMP packet with 9 bytes (last byte should be treated as 0xAB00) */
uint8_t packet[] = {
0x08, 0x00, 0x00, 0x00, /* type, code, checksum */
0x00, 0x00, 0x00, 0x00, /* id, seq */
0xAB /* 1 byte payload */
};
uint16_t result = icmp_checksum(packet, sizeof(packet));
/* Words: 0x0800, 0x0000, 0x0000, 0x0000, 0xAB00 (last byte in high)
* Sum: 0x0800 + 0x0000 + 0x0000 + 0x0000 + 0xAB00 = 0xB300
* Checksum: ~0xB300 = 0x4CFF */
cr_assert_eq(result, 0x4CFF,
"Expected checksum 0x4CFF, got 0x%04X", result);
}
/* Test 3: Verify checksum - a packet with correct checksum
* should give 0x0000 when checksummed (including the checksum field) */
Test(checksum, verify_correct_checksum)
{
/* ICMP Echo Request with correct checksum already filled in */
uint8_t packet[] = {
0x08, 0x00, 0xE5, 0xCA, /* type, code, checksum=0xE5CA */
0x12, 0x34, 0x00, 0x01 /* id=0x1234, seq=0x0001 */
};
/* When checksum is included in calculation, result should be 0 */
uint16_t result = icmp_checksum(packet, sizeof(packet));
cr_assert_eq(result, 0x0000,
"Valid packet should checksum to 0x0000, got 0x%04X", result);
}