分类: C/C++
2014-02-03 09:28:48
一个简单的HTTP协议客户端源代码
#include
#include
#include
typedef struct{
char line[256];
char head[256];
char body[256];
}message;
void main(){
int num;
SOCKET sfd;
WSADATA wsa;
struct sockaddr_in serv;
message req;
char sndBuf[1024], rcvBuf[1024];
WSAStartup(MAKEWORD(2,1),&wsa);
if((sfd=socket(AF_INET,SOCK_STREAM,0))<0){
perror("socket error!");
exit(1);
}
memset(&serv,0,sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(80);
//BING 70.37.92.127
//BAIDU 115.239.210.26
//baidu api 180.149.132.118
//google 74.125.31.99
serv.sin_addr.S_un.S_addr=inet_addr("74.125.31.99");
if((connect(sfd,(struct sockaddr *)&serv,sizeof(serv)))<0){
perror("connet error!");
exit(1);
}
memset(sndBuf,0,1024);
memset(rcvBuf,0,1024);
strcpy(req.line,"GET / HTTP/1.0\r\n");
strcat(sndBuf,req.line);
strcpy(req.head,"\r\n");
strcat(sndBuf,req.head);
puts(sndBuf);
if((num=send(sfd,sndBuf,1024,0))<0){
perror("send error!");
exit(1);
}
puts("send success!\n");
do{
if((num=recv(sfd,rcvBuf,1024,0))<0){
perror("recv error!");
exit(1);
}
else if(num>0){
printf("%s",rcvBuf);
memset(rcvBuf,0,1024);
}
}while(num>0);
puts("\nread success!\n");
closesocket(sfd);
WSACleanup();
}