1 /*
2 * Copyright 2021 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <inttypes.h>
18 #include <linux/if_ether.h>
19 #include <net/ethernet.h>
20 #include <stdio.h>
21
22 #define ETH_STRLEN (ETH_ALEN * 3)
23 #define HEX_OUT "%02" PRIx8
24 #define ETH_OUT \
25 HEX_OUT ":" HEX_OUT ":" HEX_OUT ":" HEX_OUT ":" HEX_OUT ":" HEX_OUT
26 #define HEX_IN "%2" SCNx8
27 #define ETH_IN HEX_IN ":" HEX_IN ":" HEX_IN ":" HEX_IN ":" HEX_IN ":" HEX_IN
28
to_ether_addr(const char * str,struct ether_addr * ret)29 int to_ether_addr(const char* str, struct ether_addr* ret)
30 {
31 char sentinel;
32 return sscanf(str, ETH_IN "%c", &ret->ether_addr_octet[0],
33 &ret->ether_addr_octet[1], &ret->ether_addr_octet[2],
34 &ret->ether_addr_octet[3], &ret->ether_addr_octet[4],
35 &ret->ether_addr_octet[5], &sentinel) != ETH_ALEN;
36 }
37
from_ether_addr(const struct ether_addr * addr,char * ret)38 void from_ether_addr(const struct ether_addr* addr, char* ret)
39 {
40 sprintf(ret, ETH_OUT, addr->ether_addr_octet[0], addr->ether_addr_octet[1],
41 addr->ether_addr_octet[2], addr->ether_addr_octet[3],
42 addr->ether_addr_octet[4], addr->ether_addr_octet[5]);
43 }
44
main(int argc,char * argv[])45 int main(int argc, char* argv[])
46 {
47 if (argc < 1)
48 {
49 return 1;
50 }
51 if (argc != 2)
52 {
53 fprintf(stderr, "Usage: %s <mac address>\n", argv[0]);
54 return 1;
55 }
56
57 struct ether_addr addr;
58 if (to_ether_addr(argv[1], &addr) != 0)
59 {
60 fprintf(stderr, "Invalid MAC Address: %s\n", argv[1]);
61 return 2;
62 }
63
64 char str[ETH_STRLEN];
65 from_ether_addr(&addr, str);
66 printf("%s\n", str);
67 return 0;
68 }
69