Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between struct addrinfo and struct sockaddr

People also ask

What is struct sockaddr?

sockaddr. The first structure is sockaddr that holds the socket information − struct sockaddr { unsigned short sa_family; char sa_data[14]; }; This is a generic socket address structure, which will be passed in most of the socket function calls. The following table provides a description of the member fields −

What is Ai_family?

ptr->ai_family is just an integer, a member of a struct addrinfo. ( And if you are wondering about the particular syntax of ptr-> , you can go through this question ), it will have a value of either AF_INET or AF_INET6 (Or in theory any other supported protocol)

What is Ai_flags?

ai_flags. Type: int. Flags that indicate options used in the getaddrinfo function. Supported values for the ai_flags member are defined in the Ws2def. h header file on the Windows SDK for Windows 7 and later.

What is struct Addrinfo?

C Programming/POSIX Reference/netdb. h/getaddrinfo It is the recommended interface for name resolution in building protocol independent applications and for transitioning legacy IPv4 code to the IPv6 Internet.


struct addrinfo is returned by getaddrinfo(), and contains, on success, a linked list of such structs for a specified hostname and/or service.

The ai_addr member isn't actually a struct sockaddr, because that struct is merely a generic one that contains common members for all the others, and is used in order to determine what type of struct you actually have. Depending upon what you pass to getaddrinfo(), and what that function found out, ai_addr might actually be a pointer to struct sockaddr_in, or struct sockaddr_in6, or whatever else, depending upon what is appropriate for that particular address entry. This is one good reason why they're kept "separate", because that member might point to one of a bunch of different types of structs, which it couldn't do if you tried to hardcode all the members into struct addrinfo, because those different structs have different members.

This is probably the easiest way to get this information if you have a hostname, but it's not the only way. For an IPv4 connection, you can just populate a struct sockaddr_in structure yourself, if you want to and you have the data to do so, and avoid going through the rigamarole of calling getaddrinfo(), which you might have to wait for if it needs to go out into the internet to collect the information for you. You don't have to use struct addrinfo at all.