Home > OS >  How to handle connect errno in cpp socket programming
How to handle connect errno in cpp socket programming

Time:11-11

I am new to Network Programming and am currently following Beej's Guide to get familiar with this content.

When the book was introducing the getaddrinfo() function, it told me about using gai_strerror() to interpret the error code returned to readable strings. However, the book doesn't cover the error handle method for connect() and I wonder if there is a similar function that would do the same job as what gai_strerror() does for getaddrinfo()?

Here is my code:

    if((status=connect(sockfd, res->ai_addr, res->ai_addrlen)) != 0){
        fprintf(stderr, "connect: %s\n", function_to_be_used(status));

        return 2;
    }

CodePudding user response:

From connect function reference:

If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

So, you need the following code:

fprintf(stderr, "connect: %s\n", strerror(errno));

getaddrinfo error handling is kind of exception, most API set errno on error, which can be converted to error message using strerror.

  • Related