-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDUTransmit.c
More file actions
75 lines (61 loc) · 2.19 KB
/
PDUTransmit.c
File metadata and controls
75 lines (61 loc) · 2.19 KB
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
#include "safeUtil.h"
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include "PDUTransmit.h"
#define MAXBUF 1024
//create PDU, send PDU, return data bytes sent
int sendPDU(int socketNumber, uint8_t* dataBuffer, int lengthOfData){
uint16_t h_newLen=lengthOfData+2;
uint8_t udpDataBuffer[h_newLen];
uint16_t nw_newLen = htons(h_newLen);
memcpy(udpDataBuffer,&nw_newLen,2);
memcpy(udpDataBuffer+2,dataBuffer,lengthOfData);
return safeSend(socketNumber, udpDataBuffer, h_newLen, 0);
}
int sendPDUWithFlag(int clientSocket, uint8_t flag, uint8_t* dataBuffer, int lengthOfData) {
uint16_t h_newLen=lengthOfData+3;
uint8_t udpDataBuffer[h_newLen];
// length at offset 0
uint16_t nw_newLen = htons(h_newLen);
memcpy(udpDataBuffer, &nw_newLen, 2);
//
// flag at offset 2
udpDataBuffer[2] = flag;
memcpy(udpDataBuffer + 3, dataBuffer, lengthOfData); // data starts at offset 3
//
return safeSend(clientSocket, udpDataBuffer, h_newLen, 0);
}
int sendResponseFlag(int clientSocket, uint8_t flag){
return sendPDU(clientSocket, &flag, 1); //only send the flag
}
//returns the length of the message, excluding the 2 byte PDU
int recvPDU(int clientSocket, uint8_t* dataBuffer, int bufferSize){
uint16_t PDULen=safeRecv(clientSocket, dataBuffer, 2, MSG_WAITALL);
if(PDULen<0){
return PDULen; //catch errors
}
if(PDULen==0){
return 0;
}
if(PDULen<2){
return -1; //this should not be possible, interpet it as an error
}
//aquire length of message from header
uint16_t nw_recBytes=0;
memcpy(&nw_recBytes,dataBuffer, 2);
uint16_t h_recBytes=ntohs(nw_recBytes)-2;
//
if(h_recBytes<=0){
return h_recBytes; //return iether 0 (connection closed), or -1 (error)
}
if(h_recBytes>bufferSize){
perror("MSG TO BIG");
return -1;
}
//repeat the process, but listen for full message now
h_recBytes= safeRecv(clientSocket, dataBuffer+2, h_recBytes, MSG_WAITALL);
return h_recBytes; //returns 0 for connection closed, -1 (error), or numBytes received on success
}