summaryrefslogtreecommitdiff
path: root/package/ramips/applications/hwnat/src/util.c
blob: 257202d21379d10640d3f35d189919e3b59e76fc (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
//#include <linux/fs.h>
#include <sys/ioctl.h>

int
getnext (
    char *  src,
    int     separator,
    char *  dest
)
{
    char *  c;
    int     len;

    if ( (src == NULL) || (dest == NULL) )
    {
        return -1;
    }

    c = strchr(src, separator);
    if (c == NULL)
    {
        strcpy(dest, src);
        return -1;
    }
    len = c - src;
    strncpy(dest, src, len);
    dest[len] = '\0';
    return len + 1;
}

int
str_to_mac (
    unsigned char * mac,
    char *          str
)
{
    int             len;
    char *          ptr = str;
    char            buf[128];
    int             i;

    for (i = 0; i < 5; i++)
    {
        if ((len = getnext(ptr, ':', buf)) == -1)
        {
            return 1; /* parse error */
        }
        mac[i] = strtol(buf, NULL, 16);
        ptr += len;
    }
    mac[5] = strtol(ptr, NULL, 16);

    return 0;
}

int
str_to_ip (
    unsigned long * ip,
    char *          str
)
{
    int             len;
    char *          ptr = str;
    char            buf[128];
    unsigned char   c[4];
    int             i;

    for (i = 0; i < 3; ++i)
    {
        if ((len = getnext(ptr, '.', buf)) == -1)
        {
            return 1; /* parse error */
        }
        c[i] = atoi(buf);
        ptr += len;
    }
    c[3] = atoi(ptr);
    *ip = (c[0]<<24) + (c[1]<<16) + (c[2]<<8) + c[3];
    return 0;
}