blob: 6c147deca44805c9054f1bf8c0a93cb7ef199b1d [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
Glenn L McGrath9a2d2722002-11-10 01:33:55 +00002/*
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
Rob Landleyecae66a2006-06-02 20:53:38 +000013#include "libbb.h"
14
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000015#include <string.h>
Eric Andersenab4e19a2003-01-14 08:54:08 +000016#include <net/if_arp.h>
Bernhard Reutner-Fischer9a67ca32006-04-02 21:14:19 +000017
18#include "rt_names.h"
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000019#include "utils.h"
Bernhard Reutner-Fischer9a67ca32006-04-02 21:14:19 +000020
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000021
22const 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
46int 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)) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000051 bb_error_msg("\"%s\" is invalid lladdr.", arg);
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000052 return -1;
53 }
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000054 if (len < 4) {
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000055 return -1;
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000056 }
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000057 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) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000070 bb_error_msg("\"%s\" is invalid lladdr.", arg);
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000071 return -1;
72 }
73 if (temp < 0 || temp > 255) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000074 bb_error_msg("\"%s\" is invalid lladdr.", arg);
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000075 return -1;
76 }
77 lladdr[i] = temp;
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000078 if (!cp) {
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000079 break;
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000080 }
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000081 arg = cp;
82 }
83 return i+1;
84 }
85}