xue
xue

Reputation: 2475

Understanding code snippet open_clientfd(char *hostname, char *port) from book CSAPP?

As reading the book < Computer Systems: A Programmer's Perspective > and in the chapter of Network Programming, I saw a this function:

int open_clientfd(char *hostname, char *port) {
    int clientfd;
    struct addrinfo hints, *listp, *p;

    /* Get a list of potential server addresses */
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_socktype = SOCK_STREAM;  /* Open a connection */
    hints.ai_flags = AI_NUMERICSERV;  /* ... using a numeric port arg. */
    hints.ai_flags |= AI_ADDRCONFIG;  /* Recommended for connections */
    Getaddrinfo(hostname, port, &hints, &listp);

    /* Walk the list for one that we can successfully connect to */
    for (p = listp; p; p = p->ai_next) {

        /* Create the socket descriptor */
        if ((clientfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) 
            continue; /* Socket failed, try the next */
        if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1) 
            break; /* Success */
        Close(clientfd); /* Connect failed, try another */
    } 

    /* Clean up */
    Freeaddrinfo(listp);
    if (!p) /* All connects failed */
        return -1;
    else    /* The last connect succeeded */
        return clientfd;
}

what I don't understand is here this line Close(clientfd); /* Connect failed, try another */, because if the socket create failed, it will continue, if it successed, it will just break out of the for loop, seems this line will never get a chance to execute?

Upvotes: 3

Views: 918

Answers (1)

Bodo
Bodo

Reputation: 9895

When the socket was successful you have opened a socket. If connect fails, the socket still exists and has to be closed. The next cycle of the loop will use the next address from the list which may need different parameters for the socket call. That's why the existing socket is not re-used.

Upvotes: 4

Related Questions