aboutsummaryrefslogtreecommitdiff
path: root/q6/c/server.c
blob: 4b250701e0e9d3b9a4b23d504e0a43278519c81b (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char *argv[]) {
    int sockfd;
    struct sockaddr_in servaddr, cli; 
    sockfd = socket(AF_INET, SOCK_DGRAM, 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));

    socklen_t len = sizeof(cli);
    while(1) {
        int n;
        char *buf = malloc(100);
        while(
                (n = recvfrom(sockfd, (char *)buf, 100, MSG_WAITALL, (struct sockaddr*) &cli, &len))
                > 0
             ) {
            printf("Client message: %s\n", buf);
            fflush(stdout);
            sendto(sockfd, buf, n, MSG_CONFIRM, (const struct sockaddr *) &cli, len);
        }
    }
    close(sockfd);
    return 0;
}