Skip to content

Commit 0cfb2af

Browse files
kapbhrlubos
authored andcommitted
[nrf fromtree] net: shell: Add random MAC address generation
Add option for setting a random MAC address to the net iface set_mac command. With random option a random MAC address can be assigned to an interface. [SHEL-2352]. Signed-off-by: Kapil Bhatt <kapil.bhatt@nordicsemi.no> (cherry picked from commit 8a52b64)
1 parent 78d3dec commit 0cfb2af

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

subsys/net/lib/shell/iface.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
*/
77

88
#include <zephyr/logging/log.h>
9+
#include <zephyr/random/random.h>
10+
#include <strings.h>
911
LOG_MODULE_DECLARE(net_shell);
1012

1113
#if defined(CONFIG_NET_L2_ETHERNET)
@@ -20,6 +22,9 @@ LOG_MODULE_DECLARE(net_shell);
2022

2123
#include "net_shell_private.h"
2224

25+
#define UNICAST_MASK GENMASK(7, 1)
26+
#define LOCAL_BIT BIT(1)
27+
2328
#if defined(CONFIG_NET_L2_ETHERNET) && defined(CONFIG_NET_NATIVE)
2429
struct ethernet_capabilities {
2530
enum ethernet_hw_caps capability;
@@ -536,10 +541,15 @@ static int cmd_net_set_mac(const struct shell *sh, size_t argc, char *argv[])
536541
goto err;
537542
}
538543

539-
if ((net_bytes_from_str(mac_addr, sizeof(params.mac_address), argv[2]) < 0) ||
540-
!net_eth_is_addr_valid(&params.mac_address)) {
541-
PR_WARNING("Invalid MAC address: %s\n", argv[2]);
542-
goto err;
544+
if (!strncasecmp(argv[2], "random", 6)) {
545+
sys_rand_get(mac_addr, NET_ETH_ADDR_LEN);
546+
mac_addr[0] = (mac_addr[0] & UNICAST_MASK) | LOCAL_BIT;
547+
} else {
548+
if ((net_bytes_from_str(mac_addr, sizeof(params.mac_address), argv[2]) < 0) ||
549+
!net_eth_is_addr_valid(&params.mac_address)) {
550+
PR_WARNING("Invalid MAC address: %s\n", argv[2]);
551+
goto err;
552+
}
543553
}
544554

545555
ret = net_mgmt(NET_REQUEST_ETHERNET_SET_MAC_ADDRESS, iface, &params, sizeof(params));

0 commit comments

Comments
 (0)