C语言HTTP请求GET

因对《所谓黑客揭秘》,大家都攻击代码的要求。所以我开始了为期两周的C/C++学习。由于没有任何C/C++基础,而是临时突击,所以代码肯定漏洞甚多,请观者见谅。同时欢迎拍砖或者支出代码错误,以求大家共同进步。

#include <stdio.h> #include <string.h> #include <winsock.h> #include <stdlib.h> void DownLoad(char *url){ WSADATA WsaData; SOCKET socketfd; SOCKADDR_IN addr; HOSTENT *pURL; int i=0; char myurl[BUFSIZ]; char *pHost =0,* pGet =0; char host[BUFSIZ],GET[BUFSIZ]; char Header[BUFSIZ]; FILE * pf; static char text[BUFSIZ]; if (WSAStartup(MAKEWORD(2,2),&WsaData)) { printf("The socket failed"); return; } strcpy(myurl,url); for (i=0,pHost= myurl;*pHost!='/'&&*pHost!='/0';pHost++,i++){ host[i] = *pHost; } host[i]='/0'; strcpy(GET,pHost); strnset(Header,'/0',BUFSIZ); socketfd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); pURL = gethostbyname(host); addr.sin_addr.s_addr = *((unsigned long *)pURL->h_addr); addr.sin_family = AF_INET; addr.sin_port = htons(80); strcat(Header,"GET / "); strcat(Header,GET); strcat(Header,"HTTP/1.1/r/n"); strcat(Header,"Accept: */*/r/n"); strcat(Header,"Accept-Language: zh-cn/r/n"); strcat(Header,"User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2)/r/n"); //strcat(Header,"Accept-Encoding: gzip, deflate/r/n"); strcat(Header,"Host: "); strcat(Header,host); strcat(Header,"/r/nConnection: Keep-Alive/r/n"); strcat(Header,"/r/n/r/n"); connect(socketfd,(SOCKADDR *)&addr,sizeof(addr)); send(socketfd,Header,strlen(Header),0); printf("%s",Header); pf = fopen("1.txt","w"); while(recv(socketfd,text,BUFSIZ,0)>0){ printf("%s",text); fputs(text,pf); strnset(text,'/0',BUFSIZ); } fclose(pf); closesocket(socketfd); WSACleanup(); } int main(){ char a[256]; printf("http://"); scanf("%s",a); DownLoad(a); }

你可能感兴趣的:(c,.net,socket,header,语言,download)