From 4d60b8da9cdcd4716fe65c8872ec60a14d2c1e48 Mon Sep 17 00:00:00 2001 From: Oskar Date: Sun, 2 Jun 2024 21:32:41 +0200 Subject: listen-DGRAM which is basically a version of listen but with UDP --- listen-DGRAM.c | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 listen-DGRAM.c (limited to 'listen-DGRAM.c') diff --git a/listen-DGRAM.c b/listen-DGRAM.c new file mode 100644 index 0000000..6110aa5 --- /dev/null +++ b/listen-DGRAM.c @@ -0,0 +1,90 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define __FAIL EXIT_FAILURE +#define BACKLOG 2 + +size_t bytes_recieved = 0; + +void INThandler() { + + fprintf(stderr, " SIGINT\n"); + fprintf(stdout, "bytes recieved: %ld\n", bytes_recieved); + exit(0); +} + +int main () { + + int sockfd = -1; // socket fd + int gai_result; // result from getaddrinfo + int bind_result = -1; // result from bind + struct addrinfo *res; // Pointer to linked list sent back by gai + struct addrinfo *p; // for linked list stuff + struct addrinfo hints; // Options we pass to gai + memset(&hints, 0, sizeof(hints)); // We set this struct to 0 and then give it all the options we want below + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_flags = AI_PASSIVE; + + gai_result = getaddrinfo(NULL, "62000", &hints, &res); // NULL because we are going to listen + if (gai_result != 0) { + fprintf(stderr, "gai_result: %d\n", gai_result); + exit(__FAIL); + } + + for (p = res ; p != NULL ; p = p->ai_next) { // Loop + + sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); // Socket, get the family, socktype and protocol. + if (sockfd == -1) { + fprintf(stderr, "sockfd: %d\n", sockfd); + continue; + } + + bind_result = bind(sockfd, p->ai_addr, p->ai_addrlen); // Bind to socket fd. pass our own address (ai_addr) and the length + if (bind_result != 0) { + fprintf(stderr, "bind_result: %d\n", bind_result); + close(sockfd); + continue; + } + } + if (sockfd == -1 || bind_result == -1) { + exit(__FAIL); + } + + freeaddrinfo(res); // free the info because we dont need it anymore + + fprintf(stdout, "Listening...\n"); + + struct sockaddr_storage from; + socklen_t fromlen = sizeof(struct sockaddr_storage); + size_t rlen = 1024; + int recv_ret; + + signal(SIGINT, INThandler); + while(true) { + + char recvmsg[rlen]; + recv_ret = recvfrom(sockfd, recvmsg, rlen, 0, (struct sockaddr *)&from, &fromlen); + bytes_recieved = bytes_recieved+recv_ret; + if (recv_ret < 1) { + break; + } + recvmsg[recv_ret] = '\0'; + fprintf(stdout, "%s", recvmsg); + //fprintf(stdout, "loop"); + memset(&recvmsg, 0, rlen); + } + + return 0; +} -- cgit v1.2.3