milanseitler
milanseitler

Reputation: 765

How to handle inet_ntop() failure?

First of all, my code example:

cout << "bla1" << endl;
struct addrinfo hints, *info;
int status;

memset(&hints, 0, sizeof hints);

char ip4[INET_ADDRSTRLEN];
char ip6[INET6_ADDRSTRLEN];

hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;

cout << "bla2" << endl;

status = getaddrinfo(url.c_str(), NULL, &hints, &info);

cout << "bla3" << endl;

if(!inet_ntop(AF_INET, &((const sockaddr_in *)info->ai_addr)->sin_addr , ip4, INET_ADDRSTRLEN)) {
  return ERROR_PAR;
}

cout << "bla4" << endl;

url variable contains the adress to be resolved (I'm working on simple client/server DNS resolver). If it can be resolved, everything works fine, however when the url can't be resolved, my output is only

bla1 bla2 bla3

The code above is in forked child so it doesn't stop the whole script, it just goes back to the parent process, no error though (I'm testing the return value, in this case it should be ERROR_PAR = 1 so the error message should appear).

Is there something wrong about the way I use these functions or the problem must be somewhere else?

EDIT: It's important to check getaddrinfo return value before any other functions. So the problem is solved.

Upvotes: 0

Views: 2370

Answers (1)

Bacon
Bacon

Reputation: 1844

To formally answer this, check the manual:

On success, inet_ntop() returns a non-null pointer to dst. NULL is returned if there was an error, with errno set to indicate the error.

So you would do something like:

#include <arpa/inet.h>
#include <stdio.h>                                                                                                                                                                                                 
#include <string.h>
#include <errno.h>

int main(void) {
    char *ip = "127.0.0.1";
    uint32_t src;
    inet_pton(AF_INET, ip, &src);

    char dst[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET, &src, dst, INET_ADDRSTRLEN)) {
        printf("converted value = %s \n", dst);   
        return 0;                                                                                                                                        
    } else {
        printf("inet_ntop conversion error: %s\n", strerror(errno));
        return 1;
    }
}

Upvotes: 1

Related Questions