summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/socket_udp/server.c
blob: 99e0ecb98a82bb1c1fd13c84983170fab595d0f6 (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
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

int
main(int argc, char* argv[])
{
    int sockfd;
    struct sockaddr_in addr;
    socklen_t addrlen;
    char buffer[1024];
    int nbytes;

    if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("Error creating a new socket");
        exit(1);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;
    addrlen = sizeof(addr);

    if (bind(sockfd, (struct sockaddr*)&addr, addrlen) == -1) {
        perror("Can't bind this socket");
        exit(1);
    }

    while ((nbytes = recv(sockfd, buffer, 1024, 0)) != 0) {
        if (nbytes == -1) {
            perror("Error receiving data");
        }
        buffer[nbytes] = '\0';

        printf("%s\n", buffer);
    }

    close(sockfd);
    return 0;
}