ll_addr.c 1.6 KB

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