Program for when a structure declaration occurs in different places

0

Follow the source code ...

#define _WIN32_WINNT 0x0501

#include <stdio.h>
#include <ws2tcpip.h>
#include <winsock.h>
#include <windows.h>

WSADATA data;

struct addrinfo tips, *information;
void exaple_one(void);
void exaple_two(void);

void main(void) {

    printf("chamando o exemplo dois\n");
    exaple_two();
    printf("chamando o exemplo um = ERROR\n");
    exaple_one();
}

void exaple_one(void) {

    struct addrinfo tips, *information;

    WORD wRequestedVersion = MAKEWORD(1, 1);
    int iResult = WSAStartup(wRequestedVersion, &data);
    char localaddr[255];
    if(iResult == SOCKET_ERROR) {
        printf("Error...!");
    }

    getaddrinfo("www.netflix.com", NULL, &tips, &information);
    struct addrinfo *ponteiro;
    ponteiro = information;
    getnameinfo(ponteiro->ai_addr, ponteiro->ai_addrlen, localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST);
    printf("exaple one address = %s\n", localaddr);
}

void exaple_two(void) {

    WORD wRequestedVersion = MAKEWORD(1, 1);
    int iResult = WSAStartup(wRequestedVersion, &data);
    char localaddr[255];
    if(iResult == SOCKET_ERROR) {
        printf("Error...!");
    }

    getaddrinfo("www.netflix.com", NULL, &tips, &information);
    struct addrinfo *ponteiro;
    ponteiro = information;
    getnameinfo(ponteiro->ai_addr, ponteiro->ai_addrlen, localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST);
    printf("example two address = %s\n", localaddr);
}

If you compile and run the above program will you see that the one example function for running the program could someone explain to me why this occurs?

    
asked by anonymous 19.04.2018 / 22:30

1 answer

0

The error is occurring because the struct addrinfo tips structure needs to be initialized before it is used by the getaddrinfo () function, and members ai_addrlen , ai_canonname , ai_addr , and ai_next of this structure ( addrinfo ), must be initialized with 0 or NULL .

Below is the code for the exaple_one corrected function:

void exaple_one(void) {

    struct addrinfo tips, *information;

    WORD wRequestedVersion = MAKEWORD(1, 1);
    int iResult = WSAStartup(wRequestedVersion, &data);
    char localaddr[255];
    if (iResult == SOCKET_ERROR) {
        printf("Error...!");
    }
    // *** Importante ***: "Zera" todos os componentes da estrutura
    ZeroMemory(&tips, sizeof(struct addrinfo)); 

    // "dicas" sobre o tipo de socket (não necessário)
    tips.ai_family = AF_UNSPEC;
    tips.ai_socktype = SOCK_STREAM;
    tips.ai_protocol = IPPROTO_TCP;

    getaddrinfo("www.netflix.com", NULL, &tips, &information);
    struct addrinfo *ponteiro;
    ponteiro = information;
    getnameinfo(ponteiro->ai_addr, ponteiro->ai_addrlen, localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST);
    printf("exaple one address = %s\n", localaddr);
}

More in the documentation: getaddrinfo function

    
20.04.2018 / 03:25