summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/socket_udp/server.c
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-11-02 09:15:49 +0100
committerSanto Cariotti <santo@dcariotti.me>2021-11-02 09:15:49 +0100
commit97ec0740a9ee3269b358859bd45fb03dbd8a49e1 (patch)
tree76d3a455d770854fed3b39bc8e6105ec6838c93a /Year_3/TSDWL/socket_udp/server.c
parent5496448b6a2a06e774ad93918b18415972e33fdc (diff)
tsdwl: add socket udp client/server
Diffstat (limited to 'Year_3/TSDWL/socket_udp/server.c')
-rw-r--r--Year_3/TSDWL/socket_udp/server.c43
1 files changed, 43 insertions, 0 deletions
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 <arpa/inet.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+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;
+}