summaryrefslogtreecommitdiff
path: root/Year_3
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-11-23 21:06:52 +0100
committerSanto Cariotti <santo@dcariotti.me>2021-11-23 21:06:52 +0100
commit14f0ae5e5b68c78cef56e80d630d1a4611a2835f (patch)
treedf532a18a8d5dd57bbb854bdbb7ddb9cea230991 /Year_3
parent5985b13797106e1caf3bb195e52e431dfe188512 (diff)
tsdwl: add exam
Diffstat (limited to 'Year_3')
-rw-r--r--Year_3/TSDWL/ex_20131219/socket.c95
1 files changed, 95 insertions, 0 deletions
diff --git a/Year_3/TSDWL/ex_20131219/socket.c b/Year_3/TSDWL/ex_20131219/socket.c
new file mode 100644
index 0000000..452aa6e
--- /dev/null
+++ b/Year_3/TSDWL/ex_20131219/socket.c
@@ -0,0 +1,95 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <string.h>
+#include <time.h>
+
+char* V[10];
+
+int
+main()
+{
+ int sockfd, clientfd;
+ struct sockaddr_in addr;
+ socklen_t addrlen;
+ int n;
+ char buffer[256];
+ int vi;
+ int i;
+ int is_present;
+ int x_rand;
+
+ srand(time(NULL));
+
+ if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
+ perror("socket");
+ exit(1);
+ }
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INADDR_ANY;
+ addr.sin_port = htons(7777);
+
+ addrlen = sizeof(addr);
+ if (bind(sockfd, (struct sockaddr*) &addr, addrlen) == -1) {
+ perror("bind");
+ exit(1);
+ }
+
+ if (listen(sockfd, 1) == -1) {
+ perror("listen");
+ exit(1);
+ }
+
+ for (i = 0; i < 10; ++i) {
+ V[i] = malloc(sizeof(char) * 255);
+ }
+ vi = 0;
+
+ while (1) {
+ if ((clientfd = accept(sockfd, (struct sockaddr*) &addr, &addrlen)) == -1) {
+ perror("accept");
+ continue;
+ }
+
+ if ((n = read(clientfd, buffer, sizeof(buffer))) == -1) {
+ perror("read");
+ goto client_close;
+ }
+
+ buffer[n-1] = 0;
+ if (strncmp(buffer, "LIST", 4) == 0) {
+ for (i = 0; i < vi; ++i)
+ printf("%s\n", V[i]);
+ } else {
+ is_present = 0;
+ for (i = 0; i < vi; ++i) {
+ if (strcmp(buffer, V[i]) == 0) {
+ is_present = 1;
+ printf("presente\n");
+ }
+ }
+
+ if (!is_present) {
+ if (vi == 9) {
+ x_rand = rand() % 10;
+ strcpy(V[x_rand], buffer);
+ } else {
+ strcpy(V[vi++], buffer);
+ }
+ printf("inserita\n");
+ }
+ }
+client_close:
+ close(clientfd);
+ }
+
+ for (i = 0; i < 10; ++i) {
+ free(V[i]);
+ }
+
+ close(sockfd);
+ return 0;
+}