3

I've been using getaddrinfo for looking up socket addresses for basic socket commands. Recently, though, the addresses it returns to me are for bogus IP addresses, which I have found using inet_ntop. I've tried my code, as well as that provided in Beej's Guide, and they both produce the same results. Here's the code:

struct addrinfo hints, *info;
int status;

memset(&hints, 0, sizeof hints);

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

if(status = getaddrinfo(address, port, &hints, &info)) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
}

char ip4[INET_ADDRSTRLEN];
inet_ntop(AF_INET, info->ai_addr, ip4, INET_ADDRSTRLEN);

std::cout<<ip4<<std::endl;

No matter what address I use, it always gives me an IP of the form

16.2.x.y

where 256*x + y is equal to the port number. Has anyone ever seen this happen, or can anyone guess why it's giving me this?

glglgl
  • 89,107
  • 13
  • 149
  • 217
Xymostech
  • 9,710
  • 3
  • 34
  • 44

1 Answers1

6

Shouldn't you be passing

((sockaddr_in const *)info->ai_addr)->sin_addr

to inet_ntop?

avakar
  • 32,009
  • 9
  • 68
  • 103
  • 1
    Yeah, that might help a bit. :P Thanks! And it's actually &((const sockaddr_in *)info->ai_addr)->sin_addr – Xymostech Dec 27 '09 at 19:09