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,之前调了好久才发现出不来结果是因为这个...

转载于:https://www.cnblogs.com/wwillforever/archive/2010/10/26/1861738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值