1. 程式人生 > >Linux下網路相關結構體 struct addrinfo

Linux下網路相關結構體 struct addrinfo

一、簡介
結構體定義如下:

struct addrinfo
{
  int ai_flags;                 /* Input flags.  */
  int ai_family;                /* Protocol family for socket.  */
  int ai_socktype;              /* Socket type.  */
  int ai_protocol;              /* Protocol for socket.  */
  socklen_t ai_addrlen;         /* Length of socket address.  */
struct sockaddr *ai_addr; /* Socket address for socket. */ char *ai_canonname; /* Canonical name for service location. */ struct addrinfo *ai_next; /* Pointer to next in list. */ };

1.ai_flags
用來指定如何處理地址和名字,可取得值如下:
這裡寫圖片描述

2.ai_family
地址族,可取的值有AF_INET(IPv4) AF_INET6(IPv6) AF_UNIX(UNIX域) AF_UNSPEC(未指定)
如下:
這裡寫圖片描述

3.ai_socktype
socket的型別,主要有SOCK_STREA(流)M和SOCK_DGRAM(資料報)兩種,其它可選如下:
這裡寫圖片描述

4.ai_protocol
socket協議,引數如下:

-
IPPROTO_IP 0 IP協議
IPPROTO_IPV4 4 IPv4
IPPROTO_IPV6 41 IPv6
IPPROTO_TCP 6 TCP
IPPROTO_UDP 17 UDP

在《UNIX環境高階程式設計》中,可以使用hint來過濾上面的結構體,僅使用ai_family、ai_flags、ai_protocol和ai_socktype欄位,剩餘的整數字段必須設定為零,並且指標欄位為空。

二、程式碼展示
1)相關函式

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);
int getnameinfo(const struct sockaddr *sa, socklen_t salen,
                char *host, size_t hostlen,
                char *serv, size_t servlen, int flags);

2)getaddrinfo
此函式主要用來替代gethostbyname函式
1.程式碼

#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    int ret = -1;
    struct addrinfo *res;
    struct addrinfo hint;
    struct addrinfo *curr;
    char ipstr[16];   

    if (argc != 2) {
        printf("parameter error\n");
        return -1;
    }

    bzero(&hint, sizeof(hint));
    hint.ai_family = AF_INET;
    hint.ai_socktype = SOCK_STREAM;

    ret = getaddrinfo(argv[1], NULL, &hint, &res);
    if (ret != 0) 
    {
        printf("getaddrinfo error\n");
        return -1;
    }

    for (curr = res; curr != NULL; curr = curr->ai_next) 
    {
        inet_ntop(AF_INET,&(((struct sockaddr_in *)(curr->ai_addr))->sin_addr), ipstr, 16);
        printf("%s\n", ipstr);
    }

    freeaddrinfo(res);

    return 0;
}

2.執行

$ ./test www.baidu.com
14.215.177.38
14.215.177.39