10.9 http
tcp 传输层协议
|
http 应用层协议 端口号 80 https
www.baidu.com --> DNS \
-> 11.23.3.2 80
web服务器 --- 三次握手建立tcp连接 ---> 浏览器
ip 11.23.3.2 connect()
port 80
<--------- GET ------------
--------- 200 OK --------->
close() 短链接
长链接
(myhttp.c)
#include <stdio.h>
#include <stdlib.h>
#include <unisted.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <fcntl.h>
int socket_init();
char* get_filename(char buff[])
{
if(buff ==NULL)
{
return NULL;
}
char * s = strtok(buff," ");
if(s == NULL)
{
return NULL;
}
printf("请求方法是:%s\n",s);
s = strtok(NULL," ");
if(s == NULL)
{
return NULL;
}
return s;
}
int main()
{
int sockfd = socket_init();
assert(sockfd != -1);
while(1)
{
struct sockaddr_in caddr;
int len = sizeof(caddr);
int c = accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c < 0)
{
continue;
}
char recv_buff[512] = {0};
recv(c,recv_buff,511,0); //接受浏览器发送过来的数据
printf("read:\n%s\n",recv_buff);
char* filename = get_filename(recv_buff); //获取浏览器访问的文件名字
if(filename == NULL)
{
send(c,"err",3,0);
close(c);
continue;
}
char path[128] = {"/home/stu/c215/day21"}; //拼接路径
if(strcmp(filename,"/") == 0)
{
strcat(path,"/index.html");
}
else
{
strcat(path,filename);
}
in fd = open(patth,O_RDONLY); //打开文件
if(fd == -1)
{
send(c,"404",3,0);
close(c);
continue;
}
int filesize = lseek(fd,0,SEEK_END); //文件大小
lseek(fd,0,SEEK_SET);
char head_buff[512] = {"HTTP/1.0 200 OK\r\n"};
strcat(head_buff,"Server:myhttp\r\n");
sprintf(head_buff+strlen(head_buff)"Content-Length:%d\r\n",filesize);
strcat(head_buff,"\r\n");
send(c,head_buff,strlen(head_buff),0);
printf("send:%s\n",head_buff);
char data_buff[1024] = {0};
int num = 0;
while((num = read(fd,data_buff,1024)) > 0)
{
send(c,data_buff,num,0);
}
close(fd);
close(c);
}
}
int socket_init()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd == -1)
{
return -1;
}
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(80);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
if(res == -1)
{
return -1;
}
res = listen(sockfd,5);
if(res == -1)
{
return -1;
}
return sockfd;
}
前端网页
(文字加背景图片)
(链接跳转)
(index.html)
<html>
<head>
<meta charset=utf-8>
<title>主页<title>
</head>
<body background=6.jpg>
<a href=next.html>下一页</a><br>
<a herf=www.baidu.con>连接百度</a>
<center>
<h1>送孟浩然之广陵
<br>
<h4>故人西辞黄鹤楼,<br>
烟花三月下扬州,<br>
孤帆远影碧空尽,<br>
唯见长江天际流.<br>
</h4>
</center>
</body>
</html>
(next.html)
<body background=7.jpg>
<a href="/index.html">上一页</a>
</a>
</html>