http命令请求练习(test_for_http_request)

 

 

写了一个小程序,练练网络编程,一是为了之后要实现的一个搜索引擎,二是为了明天的trend面试和晚上的盛大笔试。God bless me!

 

代码
1 #include<sys/types.h>
2 #include<unistd.h>
3 #include<sys/socket.h>
4 #include<arpa/inet.h>
5 #include<netdb.h>
6
7 #include<stdio.h>
8 #include<string.h>
9
10
11  #define PORT 80
12  #define URL "www.seu.edu.cn"
13
14
15  int main()
16 {
17 int fd = socket(PF_INET,SOCK_STREAM,0);
18
19 if(fd < 0)
20 {
21 printf("socket error ! %m");
22 return -1;
23 }
24
25 struct sockaddr_in addr;
26 addr.sin_family = AF_INET;
27 addr.sin_port=htons(PORT);
28 struct hostent* phost;
29 in_addr_t ip_addr;
30 //the url is ip address
31   if((ip_addr=inet_addr(URL))!= INADDR_NONE)
32 {
33 addr.sin_addr.s_addr = ip_addr;
34 }
35 else
36 {
37 //find the ip address of the url
38 phost= gethostbyname(URL);
39 if(phost)
40 {
41 addr.sin_addr = *(struct in_addr*)(phost->h_addr_list)[0];
42 char addr_ip[INET_ADDRSTRLEN];
43 printf("the address is %s\n",inet_ntop(AF_INET,&(addr.sin_addr),addr_ip,INET_ADDRSTRLEN));
44 }
45 else
46 {
47 printf("gethostbyname error!\n");
48 return -2;
49 }
50 }
51
52 if(connect(fd,(struct sockaddr*)&addr,sizeof(addr))!=0)
53 {
54 printf("connect error!%m \n ");
55 return -3;
56 }
57 //Note that every request option should end with \r\n and we should add an addtional \r\n at th end of request
58 const char* request = "GET / HTTP/1.0\r\n\r\n";
59 int nwrite = write(fd,request,strlen(request)+1);
60
61 if(nwrite<0)
62 {
63 printf("write error %m \n");
64 return -3;
65 }
66
67 int nread;
68 char readbuf[1024];
69 while(nread = read(fd,readbuf,1024))
70 {
71 write(STDOUT_FILENO,readbuf,nread);
72 }
73 close(fd);
74 return 0;
75 }
76

 

注意:request的格式问题,每个命令后加\r\n,最后也要加上额外的\r\n,之前调了好久才发现出不来结果是因为这个...

posted on 2010-10-26 17:36  Weifeng Wang  阅读(722)  评论(0编辑  收藏  举报

导航