libicmp/tests/send/test_send_packet.c
2026-01-26 20:14:11 +01:00

92 lines
2.2 KiB
C

#include <criterion/criterion.h>
#include <arpa/inet.h>
#include <string.h>
#include "icmp.h"
#include "internal/icmp_internal.h"
#include "internal/icmp_send.h"
#include "test_helpers.h"
/* Test 1: Send simple packet successfully */
Test(send_packet, success)
{
if (0 == has_net_raw_capability())
{
cr_skip("Test requires CAP_NET_RAW or root privileges");
}
icmp_handle_t *h = icmp_create();
cr_assert_not_null(h);
struct icmp_handle *handle = (struct icmp_handle *)h;
/* Simple ICMP packet (type=8, code=0) */
uint8_t packet[] = {
0x08, 0x00, 0x00, 0x00, /* type, code, checksum */
0x00, 0x00, 0x00, 0x00 /* id, seq */
};
struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1");
int ret = send_packet(handle, packet, sizeof(packet), &dest);
cr_assert_eq(ret, 0, "Expected success (0)");
icmp_destroy(h);
}
/* Test 2: Invalid FD returns -1 */
Test(send_packet, invalid_fd)
{
struct icmp_handle h = {0};
h.fd = -1;
h.last_error = ICMP_OK;
h.error_msg[0] = '\0';
uint8_t packet[8] = {0};
struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1");
int ret = send_packet(&h, packet, sizeof(packet), &dest);
cr_assert_eq(ret, -1, "Expected -1 for invalid FD");
cr_assert_eq(h.last_error, ICMP_ERR_SEND,
"Error code should be ICMP_ERR_SEND");
}
/* Test 3: Send with payload */
Test(send_packet, with_payload)
{
if (0 == has_net_raw_capability())
{
cr_skip("Test requires CAP_NET_RAW or root privileges");
}
icmp_handle_t *h = icmp_create();
cr_assert_not_null(h);
struct icmp_handle *handle = (struct icmp_handle *)h;
/* ICMP packet with payload */
uint8_t packet[16] = {
0x08, 0x00, 0x00, 0x00, /* type, code, checksum */
0x00, 0x00, 0x00, 0x00, /* id, seq */
'H', 'E', 'L', 'L', 'O', 0, 0, 0 /* payload */
};
struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1");
int ret = send_packet(handle, packet, sizeof(packet), &dest);
cr_assert_eq(ret, 0, "Expected success with payload");
icmp_destroy(h);
}