From 68ab812e16e2aa114e1fafe6da05441d1c0033d6 Mon Sep 17 00:00:00 2001 From: Christian Deacon Date: Mon, 22 Apr 2024 00:01:07 -0400 Subject: [PATCH] Add get_src_mac_address() to utils. --- src/utils.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/utils.c b/src/utils.c index 7195d32..9471d2c 100644 --- a/src/utils.c +++ b/src/utils.c @@ -144,4 +144,41 @@ char *rand_ip(char *range, __u16 *pckt_count) free(cidr_str); return inet_ntoa(rand_ip_str); +} + +/** + * Retrieves the source MAC address of an interface. + * + * @param dev The interface/device name. + * @param src_mac A pointer to the source MAC address (__u8). + * + * @return 0 on success or -1 on failure (path not found). +**/ +int get_src_mac_address(const char *dev, __u8 *src_mac) +{ + // Format path to source MAC on file system using network class. + char path[255]; + snprintf(path, sizeof(path) - 1, "/sys/class/net/%s/address", dev); + + // Attempt to open path/file and check. + FILE *fp = fopen(path, "r"); + + if (!fp) + { + return -1; + } + + // Create buffer to copy contents of file to. + char buffer[255]; + + // Copy contents of file to buffer. + fgets(buffer, sizeof(buffer), fp); + + // Scan MAC address. + sscanf(buffer, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &src_mac[0], &src_mac[1], &src_mac[2], &src_mac[3], &src_mac[4], &src_mac[5]); + + // Close file. + fclose(fp); + + return 0; } \ No newline at end of file