ll_addr.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of the GNU General Public License
  5. * as published by the Free Software Foundation; either version
  6. * 2 of the License, or (at your option) any later version.
  7. *
  8. * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
  9. */
  10. #include <net/if_arp.h>
  11. #include "libbb.h"
  12. #include "rt_names.h"
  13. #include "utils.h"
  14. const char* FAST_FUNC ll_addr_n2a(unsigned char *addr, int alen, int type, char *buf, int blen)
  15. {
  16. int i;
  17. int l;
  18. if (alen == 4
  19. && (type == ARPHRD_TUNNEL || type == ARPHRD_SIT || type == ARPHRD_IPGRE)
  20. ) {
  21. return inet_ntop(AF_INET, addr, buf, blen);
  22. }
  23. l = 0;
  24. for (i = 0; i < alen; i++) {
  25. if (i == 0) {
  26. snprintf(buf + l, blen, ":%02x"+1, addr[i]);
  27. blen -= 2;
  28. l += 2;
  29. } else {
  30. snprintf(buf + l, blen, ":%02x", addr[i]);
  31. blen -= 3;
  32. l += 3;
  33. }
  34. }
  35. return buf;
  36. }
  37. int FAST_FUNC ll_addr_a2n(unsigned char *lladdr, int len, char *arg)
  38. {
  39. int i;
  40. if (strchr(arg, '.')) {
  41. inet_prefix pfx;
  42. if (get_addr_1(&pfx, arg, AF_INET)) {
  43. bb_error_msg("\"%s\" is invalid lladdr", arg);
  44. return -1;
  45. }
  46. if (len < 4) {
  47. return -1;
  48. }
  49. memcpy(lladdr, pfx.data, 4);
  50. return 4;
  51. }
  52. for (i = 0; i < len; i++) {
  53. int temp;
  54. char *cp = strchr(arg, ':');
  55. if (cp) {
  56. *cp = 0;
  57. cp++;
  58. }
  59. if (sscanf(arg, "%x", &temp) != 1 || (temp < 0 || temp > 255)) {
  60. bb_error_msg("\"%s\" is invalid lladdr", arg);
  61. return -1;
  62. }
  63. lladdr[i] = temp;
  64. if (!cp) {
  65. break;
  66. }
  67. arg = cp;
  68. }
  69. return i+1;
  70. }