Skip to content
This repository was archived by the owner on Feb 20, 2025. It is now read-only.

Commit 68ab812

Browse files
committed
Add get_src_mac_address() to utils.
1 parent 7d66956 commit 68ab812

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/utils.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,41 @@ char *rand_ip(char *range, __u16 *pckt_count)
144144
free(cidr_str);
145145

146146
return inet_ntoa(rand_ip_str);
147+
}
148+
149+
/**
150+
* Retrieves the source MAC address of an interface.
151+
*
152+
* @param dev The interface/device name.
153+
* @param src_mac A pointer to the source MAC address (__u8).
154+
*
155+
* @return 0 on success or -1 on failure (path not found).
156+
**/
157+
int get_src_mac_address(const char *dev, __u8 *src_mac)
158+
{
159+
// Format path to source MAC on file system using network class.
160+
char path[255];
161+
snprintf(path, sizeof(path) - 1, "/sys/class/net/%s/address", dev);
162+
163+
// Attempt to open path/file and check.
164+
FILE *fp = fopen(path, "r");
165+
166+
if (!fp)
167+
{
168+
return -1;
169+
}
170+
171+
// Create buffer to copy contents of file to.
172+
char buffer[255];
173+
174+
// Copy contents of file to buffer.
175+
fgets(buffer, sizeof(buffer), fp);
176+
177+
// Scan MAC address.
178+
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]);
179+
180+
// Close file.
181+
fclose(fp);
182+
183+
return 0;
147184
}

0 commit comments

Comments
 (0)