getaddrinfo函数

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

getaddrinfo, freeaddrinfo, gai_strerror - network address and service translation

函数声明

#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 结构体

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;
};

示例

#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: 178 tags: c