-
Notifications
You must be signed in to change notification settings - Fork 3
/
packet.c
executable file
·97 lines (76 loc) · 1.54 KB
/
packet.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <packet.h>
packet_t* alloc_packet(unsigned int size, char* data)
{
packet_t* packet = malloc(sizeof(*packet));
packet->size = size;
packet->data = data;
return packet;
}
void free_packet(packet_t* packet)
{
free(packet->data);
free(packet);
}
int send_packet(int to, packet_t *packet)
{
int err;
if (packet->size > MAX_PACKET_SIZE) {
packet->size = MAX_PACKET_SIZE;
printf("Packet too big!\n");
}
err = send(to, &packet->size, sizeof(packet->size), 0);
if (err < 0) {
perror("send_packet:send size:");
return err;
}
err = send(to, packet->data, packet->size, 0);
if (err < 0) {
perror("send_packet:send_data:");
return err;
}
return err;//number of written bytes not error
}
int send_packet_native(int to, packet_t* packet)
{
int err;
err = write(to, packet->data, packet->size);
if (err < 0) {
perror("send_packet_native:send_data:");
return err;
}
return err;
}
packet_t* recv_packet(int from)
{
int size;
char *data;
int err;
err = read(from, &size, sizeof(size));
if (err < 0) {
return NULL;
}
data = malloc(size);
err = read(from, data, size);
if (err < 0) {
return NULL;
}
if (size > MAX_PACKET_SIZE) {
printf("Packet to big!\n");
size = MAX_PACKET_SIZE;
}
return alloc_packet(size, data);
}
packet_t* recv_packet_native(int from)
{
int size;
char *data = malloc(MAX_PACKET_SIZE);
size = read(from, data, MAX_PACKET_SIZE);
if (size < 0) {
return NULL;
}
return alloc_packet(size, data);
}