-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathl2.c
113 lines (90 loc) · 2.32 KB
/
l2.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
108
109
110
111
112
113
// l2.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#define MAX_LENGTH 1024
// Interface to Layer 1
extern int l1_read(char* b);
extern int l1_write(char b);
// l2 function declarations
int build_l2_packet(char* l2_buf, int* l2_length, char* buffer, int length);
int read_l2_packet(char* buffer, int* maxlength, char* length_buf);
int l2_read(char* buffer, int maxlength)
{
char length_buf[2];
// Read the length from the header
for (int i = 0; i < 2; i++)
{
if (l1_read(&length_buf[i]) == -1)
{
perror("l1_read");
return -1;
}
}
if (read_l2_packet(buffer, &maxlength, length_buf) == 0)
{
return -1;
}
return maxlength;
}
int l2_write(char* buffer, int length)
{
char l2_buf[MAX_LENGTH + 2];
int l2_length = 0;
// Build the L2 packet
if (build_l2_packet(l2_buf, &l2_length, buffer, length) == 0)
{
return -1;
}
// output packet
for (int i = 0; i < l2_length; i++)
{
if (l1_write(l2_buf[i]) == -1)
{
perror("l1_write");
return -1;
};
}
return length;
}
int build_l2_packet(char* l2_buf, int* l2_length, char* buffer, int length)
{
if (length > MAX_LENGTH)
{
fprintf(stderr, "l2 Error -- The message cannot be longer than %d bytes\n", MAX_LENGTH);
return 0;
}
uint16_t uint16_length = htons((uint16_t)length);
memcpy(l2_buf, &uint16_length, sizeof(uint16_t));
memcpy(l2_buf + sizeof(uint16_t), buffer, length);
*l2_length = length + 2;
return 1;
}
int read_l2_packet(char* buffer, int* maxlength, char* length_buf)
{
// Convert the length
uint16_t uint16_length;
memcpy(&uint16_length, length_buf, sizeof(uint16_t));
int length = (int)ntohs(uint16_length);
if(length > MAX_LENGTH) {
fprintf(stderr, "l2 Error -- The message cannot be longer than %d bytes\n", MAX_LENGTH);
return 0;
}
if (length > *maxlength)
{
fprintf(stderr, "l2 Error -- buffer size exceeds length\n");
return 0;
}
// Read the packet
for (int i = 0; i < length; i++)
{
if (l1_read(&buffer[i]) == -1)
{
perror("l1_read");
return 0;
}
}
*maxlength = length;
return 1;
}