-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
82 lines (68 loc) · 1.4 KB
/
util.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
#include "util.h"
int str_separate(char *srcstr, char sep, char ***output)
{
int len = strlen(srcstr);
int numparts = 0;
char temp[100];
strcpy(temp, srcstr);
char **currentpart;
int i;
for (i = 0; i < len; i++)
{
if (temp[i] == sep)
{
temp[i] = '\0';
numparts++;
}
}
numparts++;
*output = malloc(numparts * sizeof(char *));
if (*output == NULL)
{
perror("malloc() call in str_separate");
exit(1);
}
currentpart = *output;
*currentpart = temp;
for (i = 0; i < len; i++)
{
if (temp[i] == '\0') {
currentpart++;
*currentpart = &(temp[i+1]);
}
}
return numparts;
}
int encapsulate_packet(char *data, char *ip, char **packet)
{
int ip_len = strlen(ip);
char temp[32];
if (ip_len > 9)
sprintf(temp, "%d%s", ip_len, ip);
else
sprintf(temp, "0%d%s", ip_len, ip);
*packet = malloc(PACKETSIZE * sizeof(char *));
strcat(*packet, temp);
strcat(*packet, data);
return 0;
}
int safe_free(char **ptr)
{
strcpy(*ptr, "0");
free(*ptr);
}
int decapsulate_packet(char *packet, char **data, char **ip)
{
char temp[32]="";
int packet_len = strlen(packet);
strncpy(temp, packet, 2);
int ip_len = atoi(temp);
memset(temp, 0, 32);
strncpy(temp, packet+2, ip_len);
*ip = malloc(ip_len * sizeof(char *));
strcpy(*ip, temp);
int data_len = packet_len - ip_len - 2;
*data = malloc((data_len) * sizeof(char*));
strncpy(*data, packet + ip_len + 2, data_len);
return 0;
}