Trying to get an IP address from "www.facebook.com"
I'm using Beej's tutorial as Salem suggested, and although painful, I finally got it linked up properly with the Windows library.
While I don't get any compiler errors or warnings from this program, I get the following remark from the system with the WSAddressToString function :
Code:
WSAAddressToString failed with : 10014,
System remark : The system detected an invalid pointer address in attempting to use a pointer argument in a call.
Or at least that's what my program outputs. I'm not sure which parameter it thinks is invalid, as far as I'm concerned I used all the right ones.
Code:
#include <stdio.h>
#include <stdlib.h>
#define _WIN32_WINNT 0x0501
#include <winsock2.h>
#include <Ws2tcpip.h>
int main ( )
{
WSADATA wsaData;
if ( WSAStartup(MAKEWORD(2,2), &wsaData ) )
{
fprintf(stderr, "WSAStartup failed with : %d,\nSystem remark : %s", WSAGetLastError(), gai_strerror(WSAGetLastError()));
return 1;
}
else
printf("WSAStartup initialized!\n\n");
int status = 0;
DWORD strlen = 0;
struct addrinfo hints, * res = NULL, * temp = NULL;
struct sockaddr_in * ipv4 = NULL;
struct sockaddr_in6 * ipv6 = NULL;
char * ipver = malloc(10);
if ( !ipver )
{
perror("Malloc");
WSACleanup();
return 1;
}
memset(ipver, 0, 10);
char ipstr[INET6_ADDRSTRLEN];
memset( &hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ( (status = getaddrinfo("www.facebook.com", NULL, &hints, &res )) )
{
fprintf(stderr, "getaddrinfo failed with : %s", gai_strerror(status));
free(ipver);
WSACleanup();
return 1;
}
for ( temp = res; temp; temp = temp->ai_next, strlen = 0 )
{
if ( temp->ai_family == AF_INET )
{
ipv4 = ( struct sockaddr_in * )temp->ai_addr;
ipver = strcpy(ipver, "IPv4");
if ( WSAAddressToString( (LPSOCKADDR)ipv4, sizeof(*ipv4), NULL, ipstr, &strlen ) )
{
fprintf(stderr, "WSAAddressToString failed with : %d,\nSystem remark : %s", WSAGetLastError(), gai_strerror(WSAGetLastError()));
free(ipver);
WSACleanup();
return 1;
}
}
else
{
ipv6 = ( struct sockaddr_in6 * )temp->ai_addr;
ipver = strcpy(ipver, "IPv6");
if ( WSAAddressToString( (LPSOCKADDR)ipv6, sizeof(*ipv6), NULL, ipstr, &strlen ) )
{
fprintf(stderr, "WSAAddressToString failed with : %d,\nSystem remark : %s", WSAGetLastError(), gai_strerror(WSAGetLastError()));
free(ipver);
WSACleanup();
return 1;
}
}
printf("The IP address for \"www.facebook.com\" is...\n\n");
printf("\n%s : %s\n", ipver, ipstr);
memset(ipver, 0, 10);
}
freeaddrinfo( res );
free(ipver);
if ( !WSACleanup() )
printf("Clean up was sucessful, program exited normally!");
else
{
fprintf(stderr, "WSACleanup failed with : %d,\nSystem Remark : %s", WSAGetLastError(), gai_strerror(WSAGetLastError()));
return 1;
}
return 0;
}
Any help is appreciated.