-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfunc_str.c
108 lines (95 loc) · 2.72 KB
/
func_str.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* Copyright (c) 2005-2010 Thierry FOURNIER
* $Id: func_str.c 690 2008-03-31 18:36:43Z $
*
*/
#include "config.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#if (__NetBSD__ || __FreeBSD__ || __OpenBSD__)
# include <net/if_dl.h>
#endif
#ifdef __FreeBSD__
# define ETHER_ADDR_OCTET octet
#else
# define ETHER_ADDR_OCTET ether_addr_octet
#endif
// conversion hexa -> bin
const u_char hex_conv[103] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 19 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 29 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 39 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, /* 49 */
2, 3, 4, 5, 6, 7, 8, 9, 0, 0, /* 59 */
0, 0, 0, 0, 0, 10, 11, 12, 13, 14, /* 69 */
15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 79 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 89 */
0, 0, 0, 0, 0, 0, 0, 10, 11, 12, /* 99 */
13, 14, 15 /* 102 */
};
// convert hex string to int
int strhex_to_int(char *hex){
int ret = 0;
while(*hex != 0){
if((*hex < 'a' || *hex > 'f' ) &&
(*hex < 'A' || *hex > 'F' ) &&
(*hex < '0' || *hex > '9')){
return -1;
}
ret *= 16;
ret += hex_conv[(int)*hex];
hex++;
}
return ret;
}
// translate string mac to binary mac
int str_to_mac(char *macaddr, struct ether_addr *to_mac){
int i;
// format verification
i = 0;
while(i <= 19) {
switch(i){
case 0: case 1:
case 3: case 4:
case 6: case 7:
case 9: case 10:
case 12: case 13:
case 15: case 16:
if((macaddr[i] < 'a' || macaddr[i] > 'f' ) &&
(macaddr[i] < 'A' || macaddr[i] > 'F' ) &&
(macaddr[i] < '0' || macaddr[i] > '9')){
return -1;
}
break;
case 2:
case 5:
case 8:
case 11:
case 14:
if(macaddr[i] != ':'){
return -1;
}
break;
}
i++;
}
to_mac->ETHER_ADDR_OCTET[0] = hex_conv[(u_char)macaddr[1]];
to_mac->ETHER_ADDR_OCTET[0] += hex_conv[(u_char)macaddr[0]] * 16;
to_mac->ETHER_ADDR_OCTET[1] = hex_conv[(u_char)macaddr[4]];
to_mac->ETHER_ADDR_OCTET[1] += hex_conv[(u_char)macaddr[3]] * 16;
to_mac->ETHER_ADDR_OCTET[2] = hex_conv[(u_char)macaddr[7]];
to_mac->ETHER_ADDR_OCTET[2] += hex_conv[(u_char)macaddr[6]] * 16;
to_mac->ETHER_ADDR_OCTET[3] = hex_conv[(u_char)macaddr[10]];
to_mac->ETHER_ADDR_OCTET[3] += hex_conv[(u_char)macaddr[9]] * 16;
to_mac->ETHER_ADDR_OCTET[4] = hex_conv[(u_char)macaddr[13]];
to_mac->ETHER_ADDR_OCTET[4] += hex_conv[(u_char)macaddr[12]] * 16;
to_mac->ETHER_ADDR_OCTET[5] = hex_conv[(u_char)macaddr[16]];
to_mac->ETHER_ADDR_OCTET[5] += hex_conv[(u_char)macaddr[15]] * 16;
return 0;
}