-
Notifications
You must be signed in to change notification settings - Fork 0
/
raspUDP.cpp
52 lines (41 loc) · 1.32 KB
/
raspUDP.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
#include <stdio.h>
#include <string.h>
#include <wiringPi.h>
#include <arpa/inet.h>
#include <sys/socket.h>
const int udpPort = 1234;
int udpSocket;
int main() {
printf("Initializing WiringPi...\n");
wiringPiSetup();
printf("Creating UDP socket...\n");
udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (udpSocket == -1) {
perror("socket");
return 1;
}
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(udpPort);
serverAddr.sin_addr.s_addr = INADDR_ANY;
if (bind(udpSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
perror("bind");
return 1;
}
printf("UDP listener started on port %d\n", udpPort);
while (1) {
char buffer[256];
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
int bytesRead = recvfrom(udpSocket, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&clientAddr, &clientAddrLen);
if (bytesRead == -1) {
perror("recvfrom");
} else {
buffer[bytesRead] = '\0';
printf("Received from %s: %s\n", inet_ntoa(clientAddr.sin_addr), buffer);
}
// Add your logic and delays here as needed.
}
return 0;
}