ll_addr.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 <net/if_arp.h>
  13. #include "libbb.h"
  14. #include "rt_names.h"
  15. #include "utils.h"
  16. const char *ll_addr_n2a(unsigned char *addr, int alen, int type, char *buf, int blen)
  17. {
  18. int i;
  19. int l;
  20. if (alen == 4 &&
  21. (type == ARPHRD_TUNNEL || type == ARPHRD_SIT || type == ARPHRD_IPGRE)) {
  22. return inet_ntop(AF_INET, addr, buf, blen);
  23. }
  24. l = 0;
  25. for (i=0; i<alen; i++) {
  26. if (i==0) {
  27. snprintf(buf+l, blen, ":%02x"+1, addr[i]);
  28. blen -= 2;
  29. l += 2;
  30. } else {
  31. snprintf(buf+l, blen, ":%02x", addr[i]);
  32. blen -= 3;
  33. l += 3;
  34. }
  35. }
  36. return buf;
  37. }
  38. int ll_addr_a2n(unsigned char *lladdr, int len, char *arg)
  39. {
  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. } else {
  52. int i;
  53. for (i=0; i<len; i++) {
  54. int temp;
  55. char *cp = strchr(arg, ':');
  56. if (cp) {
  57. *cp = 0;
  58. cp++;
  59. }
  60. if (sscanf(arg, "%x", &temp) != 1) {
  61. bb_error_msg("\"%s\" is invalid lladdr", arg);
  62. return -1;
  63. }
  64. if (temp < 0 || temp > 255) {
  65. bb_error_msg("\"%s\" is invalid lladdr", arg);
  66. return -1;
  67. }
  68. lladdr[i] = temp;
  69. if (!cp) {
  70. break;
  71. }
  72. arg = cp;
  73. }
  74. return i+1;
  75. }
  76. }