From 912fe9fd05732d4e7da17f7110fe5e895ac88672 Mon Sep 17 00:00:00 2001 From: Ian Moffett Date: Wed, 24 Sep 2025 23:32:49 -0400 Subject: link: Get MAC address from specified interface Signed-off-by: Ian Moffett --- src/include/if_ether.h | 14 ++++++++++++++ src/main.c | 17 +++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/include/if_ether.h b/src/include/if_ether.h index a71bd21..0cdf2fa 100644 --- a/src/include/if_ether.h +++ b/src/include/if_ether.h @@ -44,6 +44,20 @@ struct ether_hdr { uint16_t proto; } __attribute__((packed)); +static inline mac_addr_t +mac_swap(uint8_t mac[HW_ADDR_LEN]) +{ + mac_addr_t swapped = 0; + + swapped |= (uint64_t)mac[0] << 40; + swapped |= (uint64_t)mac[1] << 32; + swapped |= (uint64_t)mac[2] << 24; + swapped |= (uint64_t)mac[3] << 16; + swapped |= (uint64_t)mac[4] << 8; + swapped |= (uint64_t)mac[5]; + return swapped; +} + /* * Load the source and dest routes into an ethernet * frame. diff --git a/src/main.c b/src/main.c index 62bf519..7372d2f 100644 --- a/src/main.c +++ b/src/main.c @@ -63,6 +63,8 @@ data_send(void) struct ether_hdr *eth; struct onet_dgram *dgram; struct ifreq ifr; + uint32_t ifidx; + mac_addr_t mac; int error, sockfd; eth = (struct ether_hdr *)data; @@ -86,13 +88,24 @@ data_send(void) return error; } + ifidx = ifr.ifr_ifindex; + + /* Grab the hardware address */ + error = ioctl(sockfd, SIOCGIFHWADDR, &ifr); + if (error < 0) { + printf("ioctl[SIOGIFHWADDR]: could not read hwaddr \"%s\"\n", iface); + return error; + } + + mac = mac_swap((void *)ifr.ifr_hwaddr.sa_data); + /* * Set up link layer sockaddr, load up the frame, datagram * and send it off. */ - saddr.sll_ifindex = ifr.ifr_ifindex; + saddr.sll_ifindex = ifidx; saddr.sll_halen = ETH_ALEN; - ether_load_route(0x54E1AD2CAE48, 0xFFFFFFFFFFFF, eth); + ether_load_route(mac, 0xFFFFFFFFFFFF, eth); dgram_load(sizeof(TEST_STR), 50, dgram); sendto( sockfd, &data, sizeof(data), 0, -- cgit v1.2.3