about getadrrinfo() C++?
Posted
by
Isavel
on Stack Overflow
See other posts from Stack Overflow
or by Isavel
Published on 2012-11-15T22:40:03Z
Indexed on
2012/11/15
23:00 UTC
Read the original article
Hit count: 134
I'm reading this book called beej's guide to network programming and there's a part in the book were it provide a sample code which illustrate the use of getaddrinfo(); the book state that the code below "will print the IP addresses for whatever host you specify on the command line" - beej's guide to network programming.
now I'm curious and want to try it out and run the code, but I guess the code was develop in UNIX environment and I'm using visual studio 2012 windows 7 OS, and most of the headers was not supported so I did a bit of research and find out that I need to include the winsock.h and ws2_32.lib for windows, for it to get working, fortunately everything compiled no errors, but when I run it using the debugger and put in 'www.google.com' as command argument I was disappointed that it did not print any ipaddress, the output that I got from the console is "getaddrinfo: E"
- what does the letter E mean?
Do I need to configure something out of the debugger?
Interestingly I left the command argument blank and the output
changed to "usage: showip hostname"
Any help would be appreciated.
#ifdef _WIN32
#endif
#include <sys/types.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
int main(int argc, char *argv[])
{
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: showip hostname\n");
system("PAUSE");
return 1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
system("PAUSE");
return 2;
}
printf("IP addresses for %s:\n\n", argv[1]);
for(p = res;p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res); // free the linked list
system("PAUSE");
return 0;
}
© Stack Overflow or respective owner