c++ - Connect() 函数错误 WSAEAFNOSUPPORT

标签 c++ sockets

如何编写 Win32 应用程序与网站通信?

我正在运行 64 位 Win7 并使用 VS 2010 C++ Express。 我正在尝试编写一个 Win32 应用程序,它将:

(1) 获取网站 URL 对应的 IP 地址,例如 www.google.com。

(2) 通过调用 WSAStartup() 建立与所需网站的连接, socket()、getaddrinfo() 和 connect() 使用正确的操作数。

(3) 通过send() 和recv() 与所需的网站通信。

我的代码如下所示。 WSAStartup()、socket() 和 getaddrinfo() 执行无错误。
函数 connect() 返回此错误: WSAEAFNO支持 “指定系列中的地址不能用于此套接字。”

我做错了什么?

//==============================================================================
// 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.
    }
  }

最佳答案

您没有在这段代码的任何地方初始化 clientService

关于c++ - Connect() 函数错误 WSAEAFNOSUPPORT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277573/

相关文章:

使用 g++ 4.6 和 boost::unordered_map 的 C++11 相关编译错误

不能包含这两个文件(WinSock2、Windows.h)

java - 服务器客户端通信卡住`[命令提示符]

c# - TcpListener 和 TcpClient 共享本地端口

c++ - UDP 客户端/服务器发送数据但无法读取

c++ - 将指针传递给结构在两个程序中的行为不同

c++ - 为什么 C++ 中的类型可转换性不具有传递性?

javascript - 如何与来自 Cheerp/js 的外部变量交互?

c++ - 为什么将音频流添加到ffmpeg的libavcodec输出容器会导致崩溃?

c++ - 为什么写入此套接字会丢弃读取缓冲区(这是真的发生了什么)?