Newer
Older
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
108
109
110
111
112
113
114
115
116
117
118
119
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include "utils.h"
static int hex2num(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static int hex2byte(const char *hex)
{
int a, b;
if((a = hex2num(*hex++)) < 0)
return -1;
if((b = hex2num(*hex++)) < 0)
return -1;
return (a << 4) | b;
}
/* convert hex string to byte array */
unsigned char *strtob(char *str, int len, unsigned char *bytes)
{
size_t i;
for (i = 0; i < len; i++) {
int a;
if ((a = hex2byte(str)) < 0)
return NULL;
str += 2;
bytes[i] = a;
}
return bytes;
}
/* convert byte array to hex string */
char *btostr(unsigned char *bytes, int len, char *str)
{
size_t i;
if (!str)
return NULL;
for (i = 0; i < len; i++)
sprintf(str + strlen(str), "%02x", bytes[i] & 0xff);
return str;
}
/* Convert "00:11:22:33:44:55" --> \x001122334455 */
unsigned char * hwaddr_aton(const char *macstr, unsigned char *mac)
{
size_t i;
for (i = 0; i < 6; i++) {
int a;
if((a = hex2byte(macstr)) < 0)
return NULL;
macstr += 2;
mac[i] = a;
if (i < 6 - 1 && *macstr++ != ':')
return NULL;
}
return mac;
}
/* Convert \x001122334455 --> "00:11:22:33:44:55" */
char * hwaddr_ntoa(const unsigned char *mac, char *macstr)
{
sprintf(macstr, "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0]&0xff, mac[1]&0xff,
mac[2]&0xff, mac[3]&0xff,
mac[4]&0xff, mac[5]&0xff);
return macstr;
}
/* install a signal handler */
int set_sighandler(int sig, void (*handler)(int))
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = handler;
if (sigaction(sig, &sa, NULL) < 0) {
fprintf(stderr, "Error sigaction %d\n", sig);
return -1;
}
return 0;
}
/* uninstall a signal handler */
int unset_sighandler(int sig)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_DFL;
return sigaction(sig, &sa, NULL);
}