您的位置:首页 > 理论基础 > 计算机网络

20 --HTTP协议的简单理解及应用

2014-09-13 09:21 573 查看
案例1:

       写一个服务器程序,接收来自浏览器的数据,并且打印

// http_s1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
int fd,cfd;
main()
{
char buf[1024];
int r;
struct sockaddr_in dr;
char strres[1024];

fd=socket(PF_INET,SOCK_STREAM,0);
if(fd==-1) printf("1:%m\n"),exit(-1);
printf("socket OK!\n");
dr.sin_family=AF_INET;
dr.sin_port=htons(6789);
dr.sin_addr.s_addr=inet_addr("120.6.111.245");

r=bind(fd,(struct sockaddr*)&dr,sizeof(dr));
if(r==-1) printf("2:%m\n"),exit(-1);
printf("bind OK!\n");

r=listen(fd,10);
if(r==-1) printf("3:%m\n"),exit(-1);
printf("listen OK!\n");

cfd=accept(fd,0,0);
if(cfd==-1) printf("4:%m\n"),exit(-1);
printf("accept OK!\n");

while(1)
{
r=recv(cfd,buf,1024,0);
if(r>0)
{
buf[r]=0;
printf("浏览器发来的请求数据:%s\n",buf);
}
else
{
break;
}

}
close(cfd);
close(fd);

}

// 在浏览器中输入:http://120.6.111.245:6789/index.html




这个是刘拉起请求服务器的信息,可以仿照这些信息进行访问大公司的网址,如访问csdn的网址

获得csdn网站的IP地址如下:





就可以知道CSDN的ip地址,一般默认的端口号都是80.

模仿浏览器的方式访问服务器:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

main()
{
int fd;
struct sockaddr_in dr;
char strreq[1024];
char buf[10*1024];
int r;
//建立socket
fd=socket(AF_INET,SOCK_STREAM,0);

//连接服务器csdnden服务器
dr.sin_family=AF_INET;
dr.sin_port=htons(80);
dr.sin_addr.s_addr=inet_addr("117.79.157.225");
r=connect(fd,(struct sockaddr*)&dr,sizeof(dr));

//构建http请求字符串
sprintf(strreq,
"GET /index.html HTTP/1.1\r\n"
"Host: 117.79.157.225:80\r\n"
"User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3\r\n"
//"Accept-Charset: gb2312,utf-8\r\n"
"Keep-Enconding: gzip,deflate\r\n"
"Connection: keep-alive\r\n"
"\r\n");
//发送http请求字符串
r=send(fd,strreq,strlen(strreq),0);
//等待服务器响应
//while(1)
//{
r=recv(fd,buf,1024,0);
//if(r<=0) break;
printf("========================\n");
printf("%s\n",buf);
printf("========================\n");
//}
close(fd);
}

显示如下:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息