Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getaddrinfo - Error: Success

Tags:

c

getaddrinfo

I am very confused.

I'm using getaddrinfo to get the address info for a given web host.

In this case, I've been using www.cmu.edu.

My code was working for a little while, but then it stopped.

The odd part is the fact that I'm clearly coming up with an error, but when the error code is printed out, it says "success."

Here are the relevant bits of code:

struct addrinfo *res = NULL;
struct addrinfo hint;

memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
hint.ai_socktype = SOCK_DGRAM;
hint.ai_flags = 0;
hint.ai_protocol = 17;

if (getaddrinfo(host, portNo, &hint, &res))
{
  perror("getaddrinfo");
  return 0;
}

Host and portNo are strings containing the host (in this case, "www.cmu.edu") and the port (in this case, "80").

They definitely contain the right thing, no extra spaces or anything like that.

Edit: Thanks everyone! I at least have an appropriate error message now, even though I still have no idea why things stopped working. The error message is:

Servname not supported for ai_socktype

I've been looking at possible causes for this error and I haven't found anything. As I said, this code was working earlier and stopped without me changing anything. I deduced that it may be the port number I was using, but I've changed it several times and nothing changed.

Any insight? I'm not attached to the port number or anything except the host. I'm just trying to get it working.

like image 902
user1174511 Avatar asked Dec 26 '22 23:12

user1174511


1 Answers

For reasons that undoubtedly made sense at the time,1getaddrinfo does not report most errors via errno, which means perror is usually unhelpful. You have to inspect its return value as well. I shall crib from wikipedia:

err = getaddrinfo("www.example.com", NULL, NULL, &result);
if (err)
{   
    if (err == EAI_SYSTEM)
        fprintf(stderr, "looking up www.example.com: %s\n", strerror(errno));
    else
        fprintf(stderr, "looking up www.example.com: %s\n", gai_strerror(err));
    return -1;
}

Incidentally, be aware that there is no consensus among implementations as to what happens if you try to look up a domain name that doesn't exist or has no A or AAAA records. You might get any of EAI_NONAME, EAI_NODATA, EAI_FAIL, or EAI_SYSTEM, or you might get success but with result set either to NULL or to a vacuous struct addrinfo. Yay. (For more detail on this, see https://sourceware.org/glibc/wiki/NameResolver .)

1 A lot of the newer POSIX APIs are trying to move away from errno, which is in the abstract a good idea, but turns out to be a headache in practice because now you have to know which functions' return value is more complicated than just 0/success, -1/error.

like image 128
zwol Avatar answered Jan 09 '23 15:01

zwol