aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 1c5c6ff8041ed018ed191ab50aa8300477784f00 (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
#include<stdio.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>

int
main()
{
    int gai_status, b_status;
    int socketfd;
    struct addrinfo hints, *res;
    char ipstr[INET6_ADDRSTRLEN];

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    gai_status = getaddrinfo(NULL, "9123", &hints, &res);
    if (gai_status != 0)
    {
        fprintf(stderr, "gai error: %s\n", gai_strerror(gai_status));
        exit(1);
    }

    socketfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (socketfd < 0)
    {
        fprintf(stderr, "socket error: %d\n", errno);
        exit(1);
    }

    b_status = bind(socketfd, res->ai_addr, res->ai_addrlen);
    if (b_status < 0)
    {
        fprintf(stderr, "bind error: %d\n", errno);
        exit(1);
    }

    inet_ntop(res->ai_family, &(((struct sockaddr_in *) res->ai_addr)->sin_addr), ipstr, sizeof ipstr);
    if (ipstr == NULL)
    {
        fprintf(stderr, "string error: %d\n", errno);
        exit(1);
    }

    printf("Endereço: %s", ipstr);

    freeaddrinfo(res);

    return 0;
}