add example for reading packages, fix functions return pointers to copy on stack

This commit is contained in:
Vinzenz Schroeter 2025-05-15 23:48:03 +02:00
parent 4ab5305377
commit 0c6efcee56
9 changed files with 86 additions and 10 deletions

View file

@ -0,0 +1,76 @@
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#include "servicepoint.h"
#define DEFAULT_LISTEN_IP "127.0.0.1"
void handle_error(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
init_env_logger();
int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_socket == -1)
handle_error("socket could not be created\n");
char *listen_addr_arg;
if (argc > 1) {
listen_addr_arg = argv[1];
} else {
listen_addr_arg = DEFAULT_LISTEN_IP;
}
struct in_addr addr;
if (inet_aton(listen_addr_arg, &addr) == 0)
handle_error("listen ip could not be parsed\n");
struct sockaddr_in sockaddrIn = {
.sin_addr = addr,
.sin_family = AF_INET,
.sin_port = htons(2342),
};
memset(sockaddrIn.sin_zero, 0, sizeof(sockaddrIn.sin_zero));
if (bind(udp_socket, (struct sockaddr *) &sockaddrIn, sizeof(sockaddrIn)) == -1)
handle_error("could not bind socket\n");
printf("socket ready to receive on %s\n", listen_addr_arg);
uint8_t buffer[10000];
bool done = false;
while (!done) {
memset(buffer, 0, sizeof(buffer));
ssize_t num_bytes = recv(udp_socket, (void *) buffer, sizeof(buffer), 0);
if (num_bytes == -1)
handle_error("could not read from client");
Packet *packet = sp_packet_try_load((ByteSlice) {
.start = buffer,
.length = num_bytes,
});
if (packet == NULL) {
printf("received invalid packet\n");
continue;
}
struct Header *header = sp_packet_get_header(packet);
ByteSlice payload = sp_packet_get_payload(packet);
printf("Received packet: cc=%d, a=%d, b=%d, c=%d, d=%d, payload=%p (len %zu)\n",
header->command_code, header->a, header->b, header->c, header->d,
payload.start, payload.length);
done = header->command_code == COMMAND_CODE_HARD_RESET;
sp_packet_free(packet);
}
exit(EXIT_SUCCESS);
}

View file

@ -1,15 +1,15 @@
#include "servicepoint.h"
#include "helpers.h"
int main() {
int main(void) {
sock_init();
int result = 0;
Bitmap *bitmap = sp_bitmap_new_max_sized();
for (int x = 0; x < sp_bitmap_width(bitmap); x++) {
for (size_t x = 0; x < sp_bitmap_width(bitmap); x++) {
sp_bitmap_fill(bitmap, false);
for (int y = 0; y < sp_bitmap_height(bitmap); y++) {
for (size_t y = 0; y < sp_bitmap_height(bitmap); y++) {
sp_bitmap_set(bitmap, (y + x) % PIXEL_WIDTH, y, true);
}