gen_ethaddr_crc.c 1.7 KB

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