如何修复找不到的getaddrinfo定义?

时间:2019-06-05 11:06:58

标签: c tcp network-programming getaddrinfo

当我尝试编译代码时,出现以下错误:

main.c:13:40: note: each undeclared identifier is reported only once for each function it appears in
main.c:17:14: error: ‘EAI_ADDRFAMILY’ undeclared (first use in this function); did you mean ‘EAI_FAMILY’?
         case EAI_ADDRFAMILY:
              ^~~~~~~~~~~~~~
              EAI_FAMILY
main.c:29:14: error: ‘EAI_NODATA’ undeclared (first use in this function); did you mean ‘EAI_NONAME’?
         case EAI_NODATA:
              ^~~~~~~~~~
              EAI_NONAME

我尝试包括不同的标头(例如netinet/in.h)以及使用不同的标准(gnu90gnu99gnu11)进行编译,但似乎没有任何解决方法错误。

以下是我的代码:

// Name: main.c
// Compile: gcc -std=gnu11 main.c
// Error:
//   main.c: In function ‘main’:
//   main.c:18:14: error: ‘EAI_ADDRFAMILY’ undeclared (first use in this function); did you mean ‘EAI_FAMILY’?
//            case EAI_ADDRFAMILY:
//                 ^~~~~~~~~~~~~~
//                 EAI_FAMILY
//   main.c:18:14: note: each undeclared identifier is reported only once for each function it appears in
//   main.c:30:14: error: ‘EAI_NODATA’ undeclared (first use in this function); did you mean ‘EAI_NONAME’?
//            case EAI_NODATA:
//                 ^~~~~~~~~~
//                 EAI_NONAME

#include <stddef.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main()
{
    struct addrinfo* res;
    char* domain = "google.com";

    switch(getaddrinfo(domain, "http", NULL, &res))
    {
        case 0:
            break;
        case EAI_ADDRFAMILY:
            break;
        case EAI_AGAIN:
            break;
        case EAI_BADFLAGS:
            break;
        case EAI_FAIL:
            break;
        case EAI_FAMILY:
            break;
        case EAI_MEMORY:
            break;
        case EAI_NODATA:
            break;
        case EAI_NONAME:
            break;
        case EAI_SERVICE:
            break;
        case EAI_SOCKTYPE:
            break;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

事实证明,尽管EAI_ADDRFAMILYEAI_NODATA这两个定义是在我的系统上的netdb.h中定义的,但它们启用,因为需要定义__USE_GNU

要(间接)启用__USE_GNU,我们在文件顶部定义_GNU_SOURCE。工作文件如下:

// Name: main.c
// Compile: gcc -std=gnu11 main.c

#define _GNU_SOURCE // Need for EAI_ADDRFAMILY and EAI_NODATA

#include <stddef.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main()
{
    struct addrinfo* res;
    char* domain = "google.com";

    switch(getaddrinfo(domain, "http", NULL, &res))
    {
        case 0:
            break;
        case EAI_ADDRFAMILY:
            break;
        case EAI_AGAIN:
            break;
        case EAI_BADFLAGS:
            break;
        case EAI_FAIL:
            break;
        case EAI_FAMILY:
            break;
        case EAI_MEMORY:
            break;
        case EAI_NODATA:
            break;
        case EAI_NONAME:
            break;
        case EAI_SERVICE:
            break;
        case EAI_SOCKTYPE:
            break;
    }

    return 0;
}