From 97ec0740a9ee3269b358859bd45fb03dbd8a49e1 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 2 Nov 2021 09:15:49 +0100 Subject: tsdwl: add socket udp client/server --- Year_3/TSDWL/socket_udp/client.c | 37 ++++++++++++++++++++++++++++++++++ Year_3/TSDWL/socket_udp/server.c | 43 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 Year_3/TSDWL/socket_udp/client.c create mode 100644 Year_3/TSDWL/socket_udp/server.c (limited to 'Year_3') diff --git a/Year_3/TSDWL/socket_udp/client.c b/Year_3/TSDWL/socket_udp/client.c new file mode 100644 index 0000000..8748db5 --- /dev/null +++ b/Year_3/TSDWL/socket_udp/client.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int +main(int argc, char* argv[]) +{ + int sockfd; + struct sockaddr_in addr; + socklen_t addrlen; + + if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) { + perror("Error with socket"); + exit(1); + } + + addr.sin_family = AF_INET; + addr.sin_port = htons(atoi(argv[1])); + if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) == -1) { + perror("Can't convert IP in bytes"); + exit(1); + } + addrlen = sizeof(addr); + + if (sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr*)&addr, addrlen) == -1) { + perror("Message not sent"); + } + + close(sockfd); + + return 0; +} diff --git a/Year_3/TSDWL/socket_udp/server.c b/Year_3/TSDWL/socket_udp/server.c new file mode 100644 index 0000000..99e0ecb --- /dev/null +++ b/Year_3/TSDWL/socket_udp/server.c @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include + +int +main(int argc, char* argv[]) +{ + int sockfd; + struct sockaddr_in addr; + socklen_t addrlen; + char buffer[1024]; + int nbytes; + + if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) { + perror("Error creating a new socket"); + exit(1); + } + + addr.sin_family = AF_INET; + addr.sin_port = htons(atoi(argv[1])); + addr.sin_addr.s_addr = INADDR_ANY; + addrlen = sizeof(addr); + + if (bind(sockfd, (struct sockaddr*)&addr, addrlen) == -1) { + perror("Can't bind this socket"); + exit(1); + } + + while ((nbytes = recv(sockfd, buffer, 1024, 0)) != 0) { + if (nbytes == -1) { + perror("Error receiving data"); + } + buffer[nbytes] = '\0'; + + printf("%s\n", buffer); + } + + close(sockfd); + return 0; +} -- cgit v1.2.3-18-g5258