【TCPIP】C语言通过Winsock下载网页内容的程序
用法是启动它然后输入URL(前缀必须是HTTP://)不要在意乱码。因为我并没有对文字编码进行处理。遇到UTF-8就会出现乱码。
但是它实现了浏览器最基本的功能:访问服务器,得到网页。
这里是代码,请收下。#include<stdio.h>
#include<winsock2.h>
#define BUF_SIZE 0x2000
int main(int argc,char**argv)
{
WSADATA wsaData;
char szUrl={0};
char szBuf={0};
if(WSAStartup(WINSOCK_VERSION,&wsaData))
{
fputs("初始化Winsock失败。\n",stderr);
return 1;
}
for(;;)
{
char *pDir=NULL;
struct hostent* hAddr=NULL;
SOCKADDR_IN sAddr={0};
SOCKET sConnect=INVALID_SOCKET;
int nSendLen=0;
int nRecv=0;
printf("请输入网址。\n");
gets(szUrl);
if(!strlen(szUrl))
{
fputs("没有输入网址,程序退出。\n",stderr);
goto BadEnd;
}
if(strnicmp(szUrl,"http://",7))
{
fputs("请输入以http://开头的网址……\n",stderr);
continue;
}
if(pDir=strchr(szUrl+7,'/'))
{
*pDir++=0;
printf("网址:%s\n目录:%s\n",szUrl+7,pDir);
}
else
printf("网址:%s\n",szUrl+7);
hAddr=gethostbyname(szUrl+7);
if(!hAddr)
{
fprintf(stderr,"域名解析失败。\nWSAGetLastError=%u\n",WSAGetLastError());
continue;
}
printf("目标IP地址:%u.%u.%u.%u\n",
(unsigned char)(hAddr->h_addr_list),
(unsigned char)(hAddr->h_addr_list),
(unsigned char)(hAddr->h_addr_list),
(unsigned char)(hAddr->h_addr_list));
sAddr.sin_family=AF_INET;
sAddr.sin_port=htons(80);
sAddr.sin_addr.s_addr=*(u_long*)(hAddr->h_addr_list);
sConnect=socket(AF_INET,SOCK_STREAM,0);
if(sConnect==INVALID_SOCKET)
{
fprintf(stderr,"无法创建SOCKET套接字。\nWSAGetLastError=%u\n",WSAGetLastError());
goto BadEnd;
}
if(connect(sConnect,(SOCKADDR*)&sAddr,sizeof(sAddr)))
{
fprintf(stderr,"无法连接。\nWSAGetLastError=%u\n",WSAGetLastError());
closesocket(sConnect);
continue;
}
if(!pDir)
pDir="";
sprintf(szBuf,
"GET /%s HTTP/1.1\n"
"Accept: text/html, application/xhtml+xml, */*\n"
"Accept-Language: zh-CN\n"
"User-Agent: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko\n"
//"Accept-Encoding: gzip, deflate\n"
"Host: %s\n"
"DNT: 1\n"
"Connection: Keep-Alive\n"
"\n"
,pDir,szUrl+7);
nSendLen=strlen(szBuf)+1;
if(send(sConnect,szBuf,nSendLen,0)!=nSendLen)
fprintf(stderr,"不能完整发送数据包。\nWSAGetLastError=%u\n",WSAGetLastError());
do
{
memset(szBuf,0,BUF_SIZE);
nRecv=recv(sConnect,szBuf,BUF_SIZE,0);
if(nRecv==SOCKET_ERROR)
nRecv=BUF_SIZE;
fwrite(szBuf,1,nRecv,stdout);
printf("%s",szBuf);
}while(nRecv==BUF_SIZE);
puts("\n");
closesocket(sConnect);
}
WSACleanup();
return 0;
BadEnd:
WSACleanup();
return 1;
}这里是工程文件的下载地址。**** Hidden Message ***** 这东西可以拿来做浏览器了 系统自动回复
页:
[1]