1. 程式人生 > >socket程式設計實現http GET請求

socket程式設計實現http GET請求

// 如果host不是點分十進位制格式,則將其轉換成點分十進位制格式
BOOL CTestDlg::GetRealIP(string& host, string& retip)
{
	retip = host;
	
	unsigned long t = inet_addr((char*)(LPCSTR)host.c_str());
	if (t == INADDR_NONE)
	{
		hostent* hostInfo = gethostbyname((char*)(LPCSTR)host.c_str());
		if (hostInfo)
		{
			struct in_addr *addr;
			addr = (struct in_addr*)hostInfo->h_addr_list[0];
			if(addr!=NULL)
			{
				retip = inet_ntoa(*addr);
			}
		}
		else
		{
			return FALSE;
		}
	}
	
	return TRUE;
}

void CTestDlg::OnButton1() 
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);

	SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
	if(INVALID_SOCKET == sock)
	{
		MessageBox("套接字建立失敗!");
	}

	char url[] = "http://www.baidu.com";
	DWORD dwServiceType;
	CString strServer, strObject;
	INTERNET_PORT nPort;
	AfxParseURL(url, dwServiceType, strServer, strObject, nPort);
	
	string host = strServer.GetBuffer(strServer.GetLength());
	strServer.ReleaseBuffer();
	string ip; // 點分十進位制格式
	GetRealIP(host, ip);
	
	struct sockaddr_in SerAddr;
	memset(&SerAddr, 0, sizeof(SerAddr));
	SerAddr.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
	SerAddr.sin_family = AF_INET;
	SerAddr.sin_port = htons(nPort);
	
	if (SOCKET_ERROR == connect(sock, (struct sockaddr*)&SerAddr, sizeof(struct sockaddr)))
		MessageBox("connect error!");
	
	char sendBuf[] = "GET http://www.baidu.com HTTP/1.1\n"
					 "Host: www.baidu.com\n\n";
	send(sock, sendBuf, sizeof(sendBuf), 0);
	
	FILE *fp = fopen("url_response.txt", "w");
	
	char buf[1024];
	while (recv(sock, buf, 1024, 0))
	{
		fwrite(buf, 1, 1024, fp);
	}
	fclose(fp);
	
	WSACleanup();
	MessageBox("Finish!");
}