Xan Nava Xan Nava - 1 year ago 65
C++ Question

c++ - What does ptr->ai_family do vs AF_INET

I am going through msdn's "Getting Started With Winsock" and they open a socket with the parameters

struct addrinfo *result = NULL,
*ptr = NULL,

iResult = getaddrinfo(


ConnectSocket = socket(
ptr->ai_family, // Address Family (address families like ipv6 ipv4)
ptr->ai_socktype, // Type (Like tcp, udp ect)
ptr->ai_protocol // Protocol to use (0 = service provider chooses)

But binarytides "Winsock tutorial" does it like this (They are using C but I have seen people do this in c++)

s = socket(

What does ptr-> do?
and why use it over just setting it like AF_INET?

Also If you have free time and know sockets well I would appreciate some help.

nos nos
Answer Source
socket(ptr->ai_family,ptr->ai_socktype, ptr->ai_protocol);

passes in variables to create the socket, instead of hard coding the values. The advantage you get is that the code works for both IPv4 and IPv6.

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)

The call to getaddrinfo() will look up the host name, and resolve it to either an IPv4 or IPv6, and you pass in the result to socket() to create a socket of the proper type. If the hostname resolves to an IPv4 host, you create a socket that can deal with IPv4, If it resolves to IPv6, you create an IPv6 socket.

If you instead hard coded the values, e.g. as AF_INET, you would only support IPv4, whilst ptr->ai_family could be either AF_INET or AF_INET6.