mac.c 897 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Copyright (c) 2017 Linus Lüssing <linus.luessing@c0d3.blue>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. * License-Filename: LICENSE
  6. */
  7. #include <linux/if_ether.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include "mac.h"
  11. #define ETH_STRLEN (sizeof("aa:bb:cc:dd:ee:ff") - 1)
  12. char mntoa_buf[ETH_STRLEN+1];
  13. int mac_aton(const char *cp, struct mac_addr *mac)
  14. {
  15. struct mac_addr m;
  16. int ret;
  17. if (strlen(cp) != ETH_STRLEN)
  18. return 0;
  19. memset(&m, 0, sizeof(m));
  20. ret = sscanf(cp, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
  21. &m.storage[0], &m.storage[1], &m.storage[2],
  22. &m.storage[3], &m.storage[4], &m.storage[5]);
  23. if (ret != ETH_ALEN)
  24. return 0;
  25. *mac = m;
  26. return 1;
  27. }
  28. char *mac_ntoa(struct mac_addr *mac)
  29. {
  30. unsigned char *m = mac->storage;
  31. snprintf(mntoa_buf, sizeof(mntoa_buf),
  32. "%02x:%02x:%02x:%02x:%02x:%02x",
  33. m[0], m[1], m[2], m[3], m[4], m[5]);
  34. return mntoa_buf;
  35. }