getaddrinfo函数

2021-03-01, updated 2021-09-12

getaddrinfo, freeaddrinfo, gai_strerror - network address and service translation

函数声明

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int getaddrinfo(const char *node, const char *service,
               const struct addrinfo *hints,
               struct addrinfo **res);

void freeaddrinfo(struct addrinfo *res);

const char *gai_strerror(int errcode);

addrinfo 结构体

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
struct addrinfo {
    int              ai_flags;
    int              ai_family;
    int              ai_socktype;
    int              ai_protocol;
    socklen_t        ai_addrlen;
    struct sockaddr *ai_addr;
    char            *ai_canonname;
    struct addrinfo *ai_next;
};

示例

 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
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <error.h>
#include <arpa/inet.h>

int main()
{

    char *host = "www.baiduffdsfsdklfjrklger.com";
    char *service = "443";
    char hostip[64] = {0};
    struct addrinfo     *ailist,*aip;
    struct addrinfo     hint;
    struct sockaddr_in  *sinp;
    const char          *addr;

    int                 err;
    int                 rt=-1;

    const char *p;
    p = "abcdef";
    printf("p:%s\n", p);
    ailist=NULL;

    hint.ai_flags=0;
    hint.ai_family=AF_INET;
    hint.ai_socktype=SOCK_STREAM;
    hint.ai_protocol=IPPROTO_TCP;
    hint.ai_addrlen=0;
    hint.ai_canonname=NULL;
    hint.ai_addr=NULL;
    hint.ai_next=NULL;
    if((err=getaddrinfo(host,service,&hint,&ailist))!=0)
    {
        printf("%s():getaddrinfo err:%s \n",__func__,gai_strerror(err));
        goto end;
    }
    for(aip=ailist;aip!=NULL; aip=aip->ai_next)
    {
        if(aip->ai_family==AF_INET)
        {
            sinp=(struct sockaddr_in *)aip->ai_addr;
            addr=inet_ntop(AF_INET,&sinp->sin_addr,hostip,INET_ADDRSTRLEN);

            if(!addr) {
                perror("inet_ntop");
            }
            printf("%s %s %d\n", __FILE__, __func__, __LINE__);
            printf(" address %s\n",addr?addr:"unknown");
            printf(" port %d\n",ntohs(sinp->sin_port));
            rt=0;
            goto end;
        }
    }

    printf("%s %s %d\n", __FILE__, __func__, __LINE__);

end:
    printf("%s %s %d\n", __FILE__, __func__, __LINE__);
    if(ailist)
        freeaddrinfo(ailist);    
    return rt;
}
words: 271 tags: c