gen_ethaddr_crc.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * (C) Copyright 2016
  4. * Olliver Schinagl <oliver@schinagl.nl>
  5. */
  6. #include <ctype.h>
  7. #include <stdbool.h>
  8. #include <stdint.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <u-boot/crc.h>
  13. #define ARP_HLEN 6 /* Length of hardware address */
  14. #define ARP_HLEN_ASCII (ARP_HLEN * 2) + (ARP_HLEN - 1) /* with separators */
  15. #define ARP_HLEN_LAZY (ARP_HLEN * 2) /* separatorless hardware address length */
  16. uint8_t nibble_to_hex(const char *nibble, bool lo)
  17. {
  18. return (strtol(nibble, NULL, 16) << (lo ? 0 : 4)) & (lo ? 0x0f : 0xf0);
  19. }
  20. int process_mac(const char *mac_address)
  21. {
  22. uint8_t ethaddr[ARP_HLEN + 1] = { 0x00 };
  23. uint_fast8_t i = 0;
  24. while (*mac_address != '\0') {
  25. char nibble[2] = { 0x00, '\n' }; /* for strtol */
  26. nibble[0] = *mac_address++;
  27. if (isxdigit(nibble[0])) {
  28. if (isupper(nibble[0]))
  29. nibble[0] = tolower(nibble[0]);
  30. ethaddr[i >> 1] |= nibble_to_hex(nibble, (i % 2) != 0);
  31. i++;
  32. }
  33. }
  34. for (i = 0; i < ARP_HLEN; i++)
  35. printf("%.2x", ethaddr[i]);
  36. printf("%.2x\n", crc8(0, ethaddr, ARP_HLEN));
  37. return 0;
  38. }
  39. void print_usage(char *cmdname)
  40. {
  41. printf("Usage: %s <mac_address>\n", cmdname);
  42. puts("<mac_address> may be with or without separators.");
  43. puts("Valid seperators are ':' and '-'.");
  44. puts("<mac_address> digits are in base 16.\n");
  45. }
  46. int main(int argc, char *argv[])
  47. {
  48. if (argc < 2) {
  49. print_usage(argv[0]);
  50. return 1;
  51. }
  52. if (!((strlen(argv[1]) == ARP_HLEN_ASCII) || (strlen(argv[1]) == ARP_HLEN_LAZY))) {
  53. puts("The MAC address is not valid.\n");
  54. print_usage(argv[0]);
  55. return 1;
  56. }
  57. if (process_mac(argv[1])) {
  58. puts("Failed to calculate the MAC's checksum.");
  59. return 1;
  60. }
  61. return 0;
  62. }