|
下面就是对www.163.com发送GET请求后接受的数据写入163com.html的简单程序
程序代码:
#include <WinSock2.h>
#include <fstream>
#pragma comment(lib,"Ws2_32.lib")
void main()
{
WORD version=MAKEWORD(1,1);
WSADATA wsaData;
int err=WSAStartup(version,&wsaData);
if ( err != 0 ) {
return;
}
if (LOBYTE(wsaData.wVersion)!=1
|| HIBYTE(wsaData.wVersion)!=1)
{
WSACleanup();
return;
}
SOCKET sock=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN sockadrr;
char *host_server="www.163.com";
hostent *pHost=gethostbyname(host_server);
LPCSTR psz=inet_ntoa (*(in_addr*)pHost->h_addr_list[0]);
sockadrr.sin_addr.S_un.S_addr=inet_addr(psz);
sockadrr.sin_family=AF_INET;
sockadrr.sin_port=htons(80);
char *Command="GET /index.html HTTP/1.1 \r\nHost: www.163.com\r\nAccept: jsp/php/asp/css/image/gif \r\n\r\n";
int len=sizeof(SOCKADDR);
connect(sock,(SOCKADDR*)&sockadrr,len);
send(sock,Command,strlen(Command)+1,MSG_DONTROUTE|MSG_OOB);
int wsaerr1=WSAGetLastError();
std::cout<<wsaerr1<<std::endl;
std::ofstream ous("D:\\163com.html",std::ios::binary);
char buf[4096];
memset(buf,0,4096);
while(recv(sock,buf,4096,0)>0)
{
if(strlen(buf)<4096)buf[strlen(buf)]=0;
ous<<buf;
}
ous.close();
int wsaerr=WSAGetLastError();
std::cout<<wsaerr<<std::endl;
} |
|