Skip to content

Commit

Permalink
Add get_src_mac_address() to utils.
Browse files Browse the repository at this point in the history
  • Loading branch information
gamemann committed Apr 22, 2024
1 parent 7d66956 commit 68ab812
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 68ab812

Please sign in to comment.