Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Linked list in struct addrinfo{} in socket programming

Tags:

c

sockets

I am reading Beejs' Guide to Network Programming

I am facing difficulty in understanding the purpose of the linkedlist i.e the final parameter in this structure:

struct addrinfo {
    int              ai_flags;     // AI_PASSIVE, AI_CANONNAME, etc.
    int              ai_family;    // AF_INET, AF_INET6, AF_UNSPEC
    int              ai_socktype;  // SOCK_STREAM, SOCK_DGRAM
    int              ai_protocol;  // use 0 for "any"
    size_t           ai_addrlen;   // size of ai_addr in bytes
    struct sockaddr *ai_addr;      // struct sockaddr_in or _in6
    char            *ai_canonname; // full canonical hostname

    struct addrinfo *ai_next;      // linked list, next node
};

What is the need of this ? next node means the next client or what?

like image 518
user2799508 Avatar asked Dec 12 '25 03:12

user2799508


1 Answers

A host can have more that one IP address. For example an IPv4 and an IPv6 address, or multiple IPv4 addresses. Therefore getaddrinfo() gives you a pointer to a linked list of one or more addrinfo structures, and ai_next is the pointer to the next element, or NULL for the last element in the list.

Example (print all IP addresses for a host):

struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo *addrs, *addr;

getaddrinfo("www.google.com", NULL, &hints, &addrs);
// addrs points to first addrinfo structure.

// Traverse the linked list:
for (addr = addrs; addr != NULL; addr = addr->ai_next) {

    char host[NI_MAXHOST];
    getnameinfo(addr->ai_addr, addr->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
    printf("%s\n", host);

}
freeaddrinfo(addrs);

(Error checking omitted for brevity.)

like image 121
Martin R Avatar answered Dec 13 '25 16:12

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!