aboutsummaryrefslogtreecommitdiff
path: root/q1/server.c
diff options
context:
space:
mode:
Diffstat (limited to 'q1/server.c')
-rw-r--r--q1/server.c64
1 files changed, 64 insertions, 0 deletions
diff --git a/q1/server.c b/q1/server.c
new file mode 100644
index 0000000..92dfad6
--- /dev/null
+++ b/q1/server.c
@@ -0,0 +1,64 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <sys/types.h>
4#include <sys/socket.h>
5#include <netinet/in.h>
6#include <unistd.h>
7#include <string.h>
8#include <arpa/inet.h>
9
10int main() {
11 int sockfd, connfd;
12 struct sockaddr_in servaddr, cli;
13
14 sockfd = socket(AF_INET, SOCK_STREAM, 0);
15 servaddr.sin_family = AF_INET;
16 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
17
18 int port = 0;
19 printf("Enter port to bind to: ");
20 scanf("%d", &port);
21 fflush(stdout);
22 fflush(stdin);
23
24 servaddr.sin_port = htons(port);
25
26 bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
27
28 listen(sockfd, 128);
29 socklen_t len = sizeof(cli);
30 printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr));
31 fflush(stdout);
32
33 connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
34 if (connfd < 0) {
35 printf("Couldn't open socket!\n");
36 close(sockfd);
37 return -1;
38 }
39
40 printf("Client connected with IP address: %s\n", inet_ntoa(cli.sin_addr));
41 fflush(stdout);
42
43 char filename[100];
44 bzero(filename, 100);
45 int n;
46 n = recv(connfd, filename, 100, 0);
47 printf("received: '%s'", filename);
48 fflush(stdout);
49
50 FILE *request_file = fopen(filename, "r");
51 if (request_file == NULL) {
52 printf("File not found: %s", filename);
53 send(connfd, "file not found", 14, 0);
54 } else {
55 char file_contents[500];
56 while(fgets(file_contents, 100, request_file)) {
57 fflush(stdout);
58 send(connfd, file_contents, 100, 0);
59 };
60 fclose(request_file);
61 }
62 fflush(stdout);
63 close(sockfd);
64}