blob: c4c44646319dd0884d6c8aa65693f893f4e764f2 [file] [log] [blame]
Glenn L McGrath9a2d2722002-11-10 01:33:55 +00001/*
2 * ll_addr.c
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
8 *
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10 */
11
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000012#include <arpa/inet.h>
13#include <string.h>
Eric Andersenab4e19a2003-01-14 08:54:08 +000014#include <net/if_arp.h>
Bernhard Reutner-Fischer9a67ca32006-04-02 21:14:19 +000015
16#include "rt_names.h"
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000017#include "utils.h"
Bernhard Reutner-Fischer9a67ca32006-04-02 21:14:19 +000018
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000019#include "libbb.h"
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000020
21const char *ll_addr_n2a(unsigned char *addr, int alen, int type, char *buf, int blen)
22{
23 int i;
24 int l;
25
26 if (alen == 4 &&
27 (type == ARPHRD_TUNNEL || type == ARPHRD_SIT || type == ARPHRD_IPGRE)) {
28 return inet_ntop(AF_INET, addr, buf, blen);
29 }
30 l = 0;
31 for (i=0; i<alen; i++) {
32 if (i==0) {
33 snprintf(buf+l, blen, "%02x", addr[i]);
34 blen -= 2;
35 l += 2;
36 } else {
37 snprintf(buf+l, blen, ":%02x", addr[i]);
38 blen -= 3;
39 l += 3;
40 }
41 }
42 return buf;
43}
44
45int ll_addr_a2n(unsigned char *lladdr, int len, char *arg)
46{
47 if (strchr(arg, '.')) {
48 inet_prefix pfx;
49 if (get_addr_1(&pfx, arg, AF_INET)) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000050 bb_error_msg("\"%s\" is invalid lladdr.", arg);
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000051 return -1;
52 }
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000053 if (len < 4) {
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000054 return -1;
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000055 }
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000056 memcpy(lladdr, pfx.data, 4);
57 return 4;
58 } else {
59 int i;
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) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000069 bb_error_msg("\"%s\" is invalid lladdr.", arg);
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000070 return -1;
71 }
72 if (temp < 0 || temp > 255) {
Manuel Novoa III cad53642003-03-19 09:13:01 +000073 bb_error_msg("\"%s\" is invalid lladdr.", arg);
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000074 return -1;
75 }
76 lladdr[i] = temp;
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000077 if (!cp) {
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000078 break;
Glenn L McGrath1b0813a2002-11-28 12:39:19 +000079 }
Glenn L McGrath9a2d2722002-11-10 01:33:55 +000080 arg = cp;
81 }
82 return i+1;
83 }
84}