Aditya Rathore
Aditya Rathore

Reputation: 21

Explain line "s = socket(res->ai_family, res->ai_socktype, res->ai_protocol)"

int s;
struct addrinfo hints, *res;

getaddrinfo("www.example.com", "http", &hints, &res);

s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

Please explain the last line of code

Upvotes: 1

Views: 332

Answers (1)

prog-fh
prog-fh

Reputation: 16920

The notion of socket is a very generic communication means. It could deal with communication between local processes, communication between your process and some internal aspects of your system's kernel (events...), communication through the network... Even when it deals with the network, there exists many protocol families and many protocols.

That's why, when we create a socket (with the socket() call on your last line), we have to provide several parameters in order to select the right properties of the required socket. man 2 socket mainly explains the first parameter (domain or protocol family) but the other parameters are explained in subsequent pages since they depend on the choice made with this first parameter.

Note that once a socket is obtained with the socket() call, you may need to provide many other settings by other system calls, depending on your intention (bind() for a server, connect() for a client... many settings exist).

In your example, it seems that you want to reach an HTTP server named www.example.com. You could have hardcoded the fact that such a server can be reached with the AF_INET protocol family (for ipv4, or AF_INET6 for ipv6), through a TCP connection (type SOCK_STREAM, protocol 0) but the getaddrinfo() function can help provide all these details and some other to be used in subsequent system calls (IP address and port number to be specified in a subsequent connect() call for example). All this information stands in the members of the returned struct addrinfo.

Upvotes: 2

Related Questions