6c147deca44805c9054f1bf8c0a93cb7ef199b1d
[oweals/busybox.git] / networking / libiproute / ll_addr.c
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
13 #include "libbb.h"
14
15 #include <string.h>
16 #include <net/if_arp.h>
17
18 #include "rt_names.h"
19 #include "utils.h"
20
21
22 const char *ll_addr_n2a(unsigned char *addr, int alen, int type, char *buf, int blen)
23 {
24         int i;
25         int l;
26
27         if (alen == 4 &&
28             (type == ARPHRD_TUNNEL || type == ARPHRD_SIT || type == ARPHRD_IPGRE)) {
29                 return inet_ntop(AF_INET, addr, buf, blen);
30         }
31         l = 0;
32         for (i=0; i<alen; i++) {
33                 if (i==0) {
34                         snprintf(buf+l, blen, "%02x", addr[i]);
35                         blen -= 2;
36                         l += 2;
37                 } else {
38                         snprintf(buf+l, blen, ":%02x", addr[i]);
39                         blen -= 3;
40                         l += 3;
41                 }
42         }
43         return buf;
44 }
45
46 int ll_addr_a2n(unsigned char *lladdr, int len, char *arg)
47 {
48         if (strchr(arg, '.')) {
49                 inet_prefix pfx;
50                 if (get_addr_1(&pfx, arg, AF_INET)) {
51                         bb_error_msg("\"%s\" is invalid lladdr.", arg);
52                         return -1;
53                 }
54                 if (len < 4) {
55                         return -1;
56                 }
57                 memcpy(lladdr, pfx.data, 4);
58                 return 4;
59         } else {
60                 int i;
61
62                 for (i=0; i<len; i++) {
63                         int temp;
64                         char *cp = strchr(arg, ':');
65                         if (cp) {
66                                 *cp = 0;
67                                 cp++;
68                         }
69                         if (sscanf(arg, "%x", &temp) != 1) {
70                                 bb_error_msg("\"%s\" is invalid lladdr.", arg);
71                                 return -1;
72                         }
73                         if (temp < 0 || temp > 255) {
74                                 bb_error_msg("\"%s\" is invalid lladdr.", arg);
75                                 return -1;
76                         }
77                         lladdr[i] = temp;
78                         if (!cp) {
79                                 break;
80                         }
81                         arg = cp;
82                 }
83                 return i+1;
84         }
85 }