xref: /linux/lib/net_utils.c (revision 1a9239bb4253f9076b5b4b2a1a4e8d7defd77a95)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/string.h>
3 #include <linux/if_ether.h>
4 #include <linux/ctype.h>
5 #include <linux/export.h>
6 #include <linux/hex.h>
7 
mac_pton(const char * s,u8 * mac)8 bool mac_pton(const char *s, u8 *mac)
9 {
10 	int i;
11 
12 	if (strnlen(s, MAC_ADDR_STR_LEN) < MAC_ADDR_STR_LEN)
13 		return false;
14 
15 	/* Don't dirty result unless string is valid MAC. */
16 	for (i = 0; i < ETH_ALEN; i++) {
17 		if (!isxdigit(s[i * 3]) || !isxdigit(s[i * 3 + 1]))
18 			return false;
19 		if (i != ETH_ALEN - 1 && s[i * 3 + 2] != ':')
20 			return false;
21 	}
22 	for (i = 0; i < ETH_ALEN; i++) {
23 		mac[i] = (hex_to_bin(s[i * 3]) << 4) | hex_to_bin(s[i * 3 + 1]);
24 	}
25 	return true;
26 }
27 EXPORT_SYMBOL(mac_pton);
28