| Brandon Kim | dab96f1 | 2021-02-18 11:21:37 -0800 | [diff] [blame^] | 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 |  | 
| William A. Kennington III | 7d6fa42 | 2021-02-08 17:04:02 -0800 | [diff] [blame] | 17 | #include <inttypes.h> | 
 | 18 | #include <net/ethernet.h> | 
 | 19 | #include <stdio.h> | 
 | 20 |  | 
 | 21 | #define ETH_STRLEN (ETH_ALEN * 3) | 
 | 22 | #define HEX_OUT "%02" PRIx8 | 
 | 23 | #define ETH_OUT                                                                \ | 
 | 24 |     HEX_OUT ":" HEX_OUT ":" HEX_OUT ":" HEX_OUT ":" HEX_OUT ":" HEX_OUT | 
 | 25 | #define HEX_IN "%2" SCNx8 | 
 | 26 | #define ETH_IN HEX_IN ":" HEX_IN ":" HEX_IN ":" HEX_IN ":" HEX_IN ":" HEX_IN | 
 | 27 |  | 
 | 28 | int to_ether_addr(const char* str, struct ether_addr* ret) | 
 | 29 | { | 
 | 30 |     char sentinel; | 
 | 31 |     return sscanf(str, ETH_IN "%c", &ret->ether_addr_octet[0], | 
 | 32 |                   &ret->ether_addr_octet[1], &ret->ether_addr_octet[2], | 
 | 33 |                   &ret->ether_addr_octet[3], &ret->ether_addr_octet[4], | 
 | 34 |                   &ret->ether_addr_octet[5], &sentinel) != ETH_ALEN; | 
 | 35 | } | 
 | 36 |  | 
 | 37 | void from_ether_addr(const struct ether_addr* addr, char* ret) | 
 | 38 | { | 
 | 39 |     sprintf(ret, ETH_OUT, addr->ether_addr_octet[0], addr->ether_addr_octet[1], | 
 | 40 |             addr->ether_addr_octet[2], addr->ether_addr_octet[3], | 
 | 41 |             addr->ether_addr_octet[4], addr->ether_addr_octet[5]); | 
 | 42 | } | 
 | 43 |  | 
 | 44 | int main(int argc, char* argv[]) | 
 | 45 | { | 
 | 46 |     if (argc < 1) | 
 | 47 |     { | 
 | 48 |         return 1; | 
 | 49 |     } | 
 | 50 |     if (argc != 2) | 
 | 51 |     { | 
 | 52 |         fprintf(stderr, "Usage: %s <mac address>\n", argv[0]); | 
 | 53 |         return 1; | 
 | 54 |     } | 
 | 55 |  | 
 | 56 |     struct ether_addr addr; | 
 | 57 |     if (to_ether_addr(argv[1], &addr) != 0) | 
 | 58 |     { | 
 | 59 |         fprintf(stderr, "Invalid MAC Address: %s\n", argv[1]); | 
 | 60 |         return 2; | 
 | 61 |     } | 
 | 62 |  | 
 | 63 |     char str[ETH_STRLEN]; | 
 | 64 |     from_ether_addr(&addr, str); | 
 | 65 |     printf("%s\n", str); | 
 | 66 |     return 0; | 
 | 67 | } |