aboutsummaryrefslogtreecommitdiff
path: root/q1/server.c
blob: 92dfad6b89c07418d6ecca45b58bfc247c075484 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

int main() {
    int sockfd, connfd; 
    struct sockaddr_in servaddr, cli; 
  
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    servaddr.sin_family = AF_INET; 
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 

    int port = 0;
    printf("Enter port to bind to: ");
    scanf("%d", &port);
    fflush(stdout);
    fflush(stdin);

    servaddr.sin_port = htons(port);
  
    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
  
    listen(sockfd, 128);
    socklen_t len = sizeof(cli);
    printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr));
    fflush(stdout);

    connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
    if (connfd < 0) {
        printf("Couldn't open socket!\n");
        close(sockfd);
        return -1;
    }

    printf("Client connected with IP address: %s\n", inet_ntoa(cli.sin_addr));
    fflush(stdout);

    char filename[100];
    bzero(filename, 100);
    int n;
    n = recv(connfd, filename, 100, 0);
    printf("received: '%s'", filename);
    fflush(stdout);

    FILE *request_file = fopen(filename, "r");
    if (request_file == NULL) {
        printf("File not found: %s", filename);
        send(connfd, "file not found", 14, 0);
    } else {
        char file_contents[500];
        while(fgets(file_contents, 100, request_file)) {
            fflush(stdout);
            send(connfd, file_contents, 100, 0);
        };
        fclose(request_file);
    }
    fflush(stdout);
    close(sockfd);
}