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