#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<netdb.h> #include<string.h> #define HTTP_PORT 80 int main(int argc,char *argv[]) { int sock; FILE *fp; char buf[BUFSIZ]; char *http_request="GET / HTTP/1.1/r/nAccept:image/jpeg/r/nAccept-Language:zh-cn/r/nAccept-Encoding:gzip,deflate/r/nAgent:Mozilla/4.0/r/nHost:www.baidu.com/r/nConnection:Keep-Alive/r/n/r/n"; struct sockaddr_in serv; struct hostent *hp; if((sock=socket(AF_INET,SOCK_STREAM,0))<0) { perror("sock error"); exit(1); } if((hp=gethostbyname("www.baidu.com"))==NULL) { perror("gethostbyname error"); exit(1); } bzero(&serv,sizeof(serv)); bcopy(hp->h_addr,&serv.sin_addr,hp->h_length); serv.sin_port=htons(HTTP_PORT); serv.sin_family=AF_INET; if(connect(sock,(struct sockaddr*)&serv,sizeof(serv))<0) { perror("connet error"); exit(1); } /*if((fp=fdopen(sock,"w"))==NULL) { perror("fdopen error"); exit(1); } */ write(sock,http_request,strlen(http_request)); if((fp=fdopen(sock,"r"))==NULL) { perror("fdopen error"); exit(1); } while(fgets(buf,BUFSIZ,fp)!=NULL) printf("%s",buf); fclose(fp); close(sock); printf("read finished!"); exit(0); }