forked from njh/EtherCard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udpserver.cpp
73 lines (63 loc) · 2.06 KB
/
udpserver.cpp
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
// Simple UDP listening server
//
// Author: Brian Lee
//
// Copyright: GPL V2
// See http://www.gnu.org/licenses/gpl.html
#include "EtherCard.h"
#include "net.h"
#define gPB ether.buffer
#define UDPSERVER_MAXLISTENERS 8 //the maximum number of port listeners.
typedef struct {
UdpServerCallback callback;
uint16_t port;
bool listening;
} UdpServerListener;
UdpServerListener listeners[UDPSERVER_MAXLISTENERS];
byte numListeners = 0;
void EtherCard::udpServerListenOnPort(UdpServerCallback callback, uint16_t port) {
if(numListeners < UDPSERVER_MAXLISTENERS)
{
listeners[numListeners] = (UdpServerListener) {
callback, port, true
};
numListeners++;
}
}
void EtherCard::udpServerPauseListenOnPort(uint16_t port) {
for(int i = 0; i < numListeners; i++)
{
if(gPB[UDP_DST_PORT_H_P] == (listeners[i].port >> 8) && gPB[UDP_DST_PORT_L_P] == ((byte) listeners[i].port)) {
listeners[i].listening = false;
}
}
}
void EtherCard::udpServerResumeListenOnPort(uint16_t port) {
for(int i = 0; i < numListeners; i++)
{
if(gPB[UDP_DST_PORT_H_P] == (listeners[i].port >> 8) && gPB[UDP_DST_PORT_L_P] == ((byte) listeners[i].port)) {
listeners[i].listening = true;
}
}
}
bool EtherCard::udpServerListening() {
return numListeners > 0;
}
bool EtherCard::udpServerHasProcessedPacket(uint16_t plen) {
bool packetProcessed = false;
for(int i = 0; i < numListeners; i++)
{
if(gPB[UDP_DST_PORT_H_P] == (listeners[i].port >> 8) && gPB[UDP_DST_PORT_L_P] == ((byte) listeners[i].port) && listeners[i].listening)
{
uint16_t datalen = (uint16_t) (gPB[UDP_LEN_H_P] << 8) + gPB[UDP_LEN_L_P] - UDP_HEADER_LEN;
listeners[i].callback(
listeners[i].port,
gPB + IP_SRC_P,
(gPB[UDP_SRC_PORT_H_P] << 8) | gPB[UDP_SRC_PORT_L_P],
(const char *) (gPB + UDP_DATA_P),
datalen);
packetProcessed = true;
}
}
return packetProcessed;
}