如何编写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()返回此错误: WSAEAFNOSUPPORT "指定系列中的地址不能与此套接字一起使用。"
我做错了什么?
//==============================================================================
// 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.
}
}
答案 0 :(得分:1)
您未在此代码中的任何位置初始化clientService
。