-
Notifications
You must be signed in to change notification settings - Fork 1
/
udpServer.c
126 lines (104 loc) · 2.7 KB
/
udpServer.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
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <mex.h>
#define BUFLEN 177
#define NUMSAMPLESRX 500
#define PORT 9930
void diep(char *s)
{
perror(s);
exit(1);
}
void udpOpen(int *s)
{
struct sockaddr_in si_me;
int s_in, i;
if ((s_in=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("socket");
printf("Open socket %d\n",s_in);
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s_in, &si_me, sizeof(si_me))==-1)
diep("bind");
memcpy(s,&s_in,sizeof(s_in));
}
void udpReceive(int s, unsigned char* data)
{
struct sockaddr_in si_other;
int slen=sizeof(si_other), st, i;
for (i=0;i<NUMSAMPLESRX;i++) {
unsigned char buf[BUFLEN];
if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
diep("recvfrom()");
st=i*BUFLEN;
memcpy(&data[st],buf,BUFLEN);
}
}
void udpClose(int s)
{
printf("Closing socket %d\n",s);
close(s);
}
/*
* void udpServer(unsigned char* data)
* {
* struct sockaddr_in si_me, si_other;
* int s, i, slen=sizeof(si_other);
* unsigned char buf[BUFLEN];
*
* if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
* diep("socket");
*
* memset((char *) &si_me, 0, sizeof(si_me));
* si_me.sin_family = AF_INET;
* si_me.sin_port = htons(PORT);
* si_me.sin_addr.s_addr = htonl(INADDR_ANY);
* if (bind(s, &si_me, sizeof(si_me))==-1)
* diep("bind");
*
*
* if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
* diep("recvfrom()");
* printf("Received packet from %s:%d\nData: %s\n\n",
* inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
*
*
* memcpy(data,buf,BUFLEN);
* close(s);
* }
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
char fun[81];
mwSize strlen=mxGetN(prhs[0])+1;
mxGetString(prhs[0],fun,strlen);
/* printf("%s\n",fun); */
if (strcmp(fun,"Open")==0) {
int *s;
plhs[0]=mxCreateNumericMatrix(1,1,mxINT64_CLASS,0);
s=mxGetData(plhs[0]);
mexLock();
udpOpen(s);
}
if (strcmp(fun,"Receive")==0) {
unsigned char* data;
int s;
plhs[0] = mxCreateNumericMatrix(1,BUFLEN*NUMSAMPLESRX, mxUINT8_CLASS, mxREAL);
data = mxGetData(plhs[0]);
s=mxGetScalar(prhs[1]);
udpReceive(s,data);
}
if (strcmp(fun,"Close")==0) {
int s;
s=mxGetScalar(prhs[1]);
udpClose(s);
mexUnlock();
}
}