ll_addr.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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* FAST_FUNC 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. ) {
  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 FAST_FUNC ll_addr_a2n(unsigned char *lladdr, int len, char *arg)
  40. {
  41. int i;
  42. if (strchr(arg, '.')) {
  43. inet_prefix pfx;
  44. if (get_addr_1(&pfx, arg, AF_INET)) {
  45. bb_error_msg("\"%s\" is invalid lladdr", arg);
  46. return -1;
  47. }
  48. if (len < 4) {
  49. return -1;
  50. }
  51. memcpy(lladdr, pfx.data, 4);
  52. return 4;
  53. }
  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 || (temp < 0 || temp > 255)) {
  62. bb_error_msg("\"%s\" is invalid lladdr", arg);
  63. return -1;
  64. }
  65. lladdr[i] = temp;
  66. if (!cp) {
  67. break;
  68. }
  69. arg = cp;
  70. }
  71. return i+1;
  72. }