The Bard of Chelsea
The Bard of Chelsea

Reputation: 45

Connect() function error WSAEAFNOSUPPORT

How do write an Win32 app to communicate with a website?

I am running 64-bit Win7 and using VS 2010 C++ Express. I am trying to write a Win32 app that will:

(1) Obtain the IP address corresponding to a website URL -- e.g., www.google.com.

(2) Establish a connection with the desired website via calls to WSAStartup(), socket(), getaddrinfo() and connect() using the proper operands.

(3) Communicate with the desired website via send() and recv().

My code is shown below. WSAStartup(), socket(), and getaddrinfo() execute w/o error.
Function connect() returns this error: WSAEAFNOSUPPORT "Addresses in the specified family cannot be used with this socket."

What am I doing wrong?

//==============================================================================
// MODULE NAME:  PrintWebPage_v003.cpp
//
// REVISION HISTORY:
// 
//   09 Jan 2014   The Bard of Chelsea
//     Original release.
// 
// DESCRIPTION:
//  
//   This module contains function PrintWebPage(). 
//   Function PrintWebPage() calls a series of Winsock functions to connect a 
//   PC-based application to an internet website.  
//
// INPUT ARGS:  n/a
//  
// OUTPUT ARG:  n/a
//  
// PERSISTENT INTERNAL VARIABLES:  Certain variables of type HFONT.
//  
// GLOBAL VARIABLES REFERENCED:  
//   blocAppInfo AppInfo 
//  
// GLOBAL VARIABLES CREATED OR MODIFIED:  None. 
//  
// WORKSPACE VARIABLES REFERENCED:  None. 
//  
// WORKSPACE VARIABLES CREATED OR MODIFIED:  None. 
//  
// FILES REFERENCED:  None. 
// 
// FILES CREATED OR MODIFIED:  None. 
//  
// REFERENCE DOCUMENTS:  None. 
//  
// LIMITATIONS:  None. 
// 
// APPLICATION NOTES:     
//
// USAGE:  PrintWebPage_v002.exe
//=======================================================================
#include "stdafx.h"
#include <Iphlpapi.h>

extern HWND hWnd;
extern HINSTANCE hInst;

#pragma comment(lib, "ws2_32.lib" )
#pragma comment(lib, "IPHLPAPI.lib")

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

/* Note: could also use malloc() and free() */

typedef struct {
    int iResult;
    int NumCodes;
    char szFcnName[60];
    char szURL[1024];
    char szMsgText[1024];
    char szResult[64];
    BOOL OpFailed;
  } clasStatusMsg, *pclasStatusMsg;

INT_PTR CALLBACK  PrintErrorMsg(HWND, UINT, WPARAM, LPARAM);

void PrintOpStatus(
    HWND hDlg
  , clasStatusMsg *pStatusMsg
  , int  StatusCode[]
  , char *szStatusCode[]
  , char *szStatusCodeMeaning[]
  )
{
  int k;
  char    tstr[1024];
  size_t  NumCharsConverted;

  strcpy(pStatusMsg->szResult,"< Not Specified >");
  sprintf(pStatusMsg->szMsgText,"Function %s() failed with unknown error.",pStatusMsg->szFcnName);
  if (StatusCode != NULL)
  {
    for (k=0; k < pStatusMsg->NumCodes; k++)
      if (pStatusMsg->iResult==StatusCode[k])
        break;
    if ( (k>=0) && (k<pStatusMsg->NumCodes) )
    {
      strcpy(pStatusMsg->szResult ,szStatusCode[k]);
      strcpy(pStatusMsg->szMsgText,szStatusCodeMeaning[k]);
    }
  }
  DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_ConnectionStatus), hDlg, PrintErrorMsg, (LPARAM)pStatusMsg);
}

int PrintWebPage(
    HWND hDlg
  , char *urlSPEC
  )
{
  HDC hdcWin;
  WSADATA wsaData; 
  char buffer[BUFFERSIZE];
  char *url = (char*)malloc(BUFFERSIZE);
  char *getMsg = { "GET / HTTP/1.0\nUser-Agent: HTTPTool/1.0\n\n" };
  SOCKET ConnectedSocket;
  int receivingContent = 1; 
  int errorValue;
  int numbytes;
  socklen_t addr_size;
  char tstr[1024];
  wchar_t wcstring[1024];
  size_t NumCharsConverted;
  RECT Rect;
  static clasStatusMsg StatusMsg;
  LPHOSTENT pHostEntity;
  int iResult;
  int iResultConnect;
  //X struct addrinfo hints;
  //X struct addrinfo *servinfo, *p;
  ADDRINFOA  hints;       
  ADDRINFOA  *servinfo, *p;
  PADDRINFOA *ppResult;
  sockaddr clientService;
  wchar_t *WebsiteIP;

  strcpy(StatusMsg.szURL,urlSPEC);

  //========================================================================
  // Initialize Winsock. 
  //========================================================================  
  #include "WSAStartup.h"

  //========================================================================
  // Get website address info. 
  //========================================================================  
  #include "GetAddrInfo.h"

  //========================================================================
  // Create a SOCKET for connecting to server
  //========================================================================  
  #include "Socket.h"

  //========================================================================
  // Connect to server.  
  //========================================================================
  #include "Connect.h"

  //------------------------------------------------------------------------
  // Error testing. 
  // urlSPEC example: www.google.com
  //------------------------------------------------------------------------
  if ((iResultConnect != SOCKET_ERROR) && (ConnectedSocket != INVALID_SOCKET)) 
  {
    //------------------------------------------------------------------------
    // Proclaim success.
    //------------------------------------------------------------------------
    StatusMsg.iResult = 0;

    sprintf(StatusMsg.szFcnName,"PrintWebPage");
    sprintf(StatusMsg.szResult ,"No Error.");
    sprintf(StatusMsg.szMsgText,"SUCCESS!  Connected to server.");
    StatusMsg.OpFailed = 0;
    DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_ConnectionStatus), hDlg, PrintErrorMsg, (LPARAM)&StatusMsg);

    //------------------------------------------------------------------------
    // Sending the http get message to the server
    //------------------------------------------------------------------------
    send(ConnectedSocket, getMsg, strlen(getMsg), 0);

    //------------------------------------------------------------------------
    // While the full content isn't downloaded keep receiving
    //------------------------------------------------------------------------
    while (receivingContent)
    {
      numbytes = recv(ConnectedSocket, buffer, BUFFERSIZE , 0);
      if(numbytes > 0)
      {
        buffer[numbytes]='\0';
        printf("%s", buffer);
      }
      else
        receivingContent = 0; //stop receiving
    }

    free(url);
    free(getMsg);
    freeaddrinfo(servinfo);
    closesocket(ConnectedSocket); //close the socket
    WSACleanup();
  }
  return 0;
}


//==============================================================================
// MODULE NAME:  WSAStartup.h
//
// REVISION HISTORY:
// 
//   09 Jan 2014   The Bard of Chelsea
//     Original release.
// 
// DESCRIPTION:
//  
//   This module defines structure to support function PrintWebPage(), which
//   is specified in module PrintWebPage_v003.cpp
//
//==============================================================================
  //========================================================================
  // Initialize Winsock 
  //   int swprintf(
  //      wchar_t *buffer,
  //      size_t count,
  //      const wchar_t *format [,
  //      argument]...
  //     
  //========================================================================
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if (iResult != NO_ERROR) 
  {
    // Error processing code removed for sake of brevity.
  }


//==============================================================================
// MODULE NAME:  Socket.h
//
// REVISION HISTORY:
// 
//   09 Jan 2014   The Bard of Chelsea
//     Original release.
// 
// DESCRIPTION:
//  
//   This module defines structure to support function PrintWebPage(), which
//   is specified in module PrintWebPage_v002.cpp
//
//==============================================================================
  //========================================================================
  // Create a SOCKET for connecting to server
  // If no error occurs, socket returns a descriptor referencing the new 
  // socket.  Otherwise, a value of INVALID_SOCKET is returned, and a 
  // specific error code can be retrieved by calling WSAGetLastError.
  //========================================================================
  ConnectedSocket = socket(
      (*ppResult)->ai_family      // Value is 2. 
    , (*ppResult)->ai_socktype    // Value is 1. 
    , (*ppResult)->ai_protocol    // Value is 0. 
    );
  StatusMsg.OpFailed = (ConnectedSocket == INVALID_SOCKET); 
  if (StatusMsg.OpFailed) 
  {
    // Error processing code removed for sake of brevity.
  }


//==============================================================================
// MODULE NAME:  GetAddrInfo.h
//
// REVISION HISTORY:
// 
//   09 Jan 2014   The Bard of Chelsea
//     Original release.
// 
// DESCRIPTION:
//  
//   This module defines structure to support function PrintWebPage(), which
//   is specified in module PrintWebPage_v002.cpp
//
//==============================================================================
  strncpy(StatusMsg.szFcnName,"gethostbyname",(sizeof StatusMsg.szFcnName));
  StatusMsg.szFcnName[int(sizeof StatusMsg.szFcnName)/2-1] = 0;
  ppResult = new PADDRINFOA;
  StatusMsg.OpFailed == getaddrinfo(
      urlSPEC  // _In_opt_  PCSTR pNodeName,        
    , "http"   // _In_opt_  PCSTR pServiceName,  80 == http
    , NULL     // _In_opt_  const ADDRINFOA *pHints,
    , ppResult // _Out_     PADDRINFOA *ppResult    
    );
  if (StatusMsg.OpFailed) 
  {
    // Error processing code removed for sake of brevity.
  }


//==============================================================================
// MODULE NAME:  Connect.h
//
// REVISION HISTORY:
//
//   09 Jan 2014   The Bard of Chelsea  
//     Original release.
//
// DESCRIPTION:
//
//   This module defines structure to support function PrintWebPage(), which 
//   is specified in module PrintWebPage_v003.cpp.  Key function is: 
//
//==============================================================================
  if (ConnectedSocket != INVALID_SOCKET)
  {
    //========================================================================
    // Connect to server
    //========================================================================
    strncpy(StatusMsg.szFcnName,"connect",(sizeof StatusMsg.szFcnName));
    StatusMsg.szFcnName[int(sizeof StatusMsg.szFcnName)/2-1] = 0;
    iResultConnect = connect(
        ConnectedSocket
      , (SOCKADDR *)(*ppResult)
      , sizeof (clientService)
      );
    if (iResultConnect == SOCKET_ERROR)
    {
      // Error processing code removed for sake of brevity.
    }
  }

Upvotes: 0

Views: 338

Answers (1)

user207421
user207421

Reputation: 310869

You're not initializing clientService anywhere in this code.

Upvotes: 1

Related Questions