aboutsummaryrefslogtreecommitdiff
path: root/q6/b/server.c
blob: e217c2bc73ddff341c751a408f2755588297497f (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
#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 argc, char *argv[]) {
    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 = atoi(argv[1]);
    servaddr.sin_port = htons(port);
  
    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
  
    listen(sockfd, 128);
    printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr));
    fflush(stdout);

    while(1) {
        socklen_t len = sizeof(cli);
        connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
        int i = getpeername(connfd, (struct sockaddr*)&cli, &len);

        printf("Client connected at port %d\n", htons(cli.sin_port));
        int n;
        char buf[100];

        while((n = recv(connfd, buf, 100, 0)) > 0) {
            printf("Client message: %s\n", buf);
            fflush(stdout);
            send(connfd, buf, n, 0);
        };
        close(connfd);
    }
    return 0;
}