非淡泊无以明志,非宁静无以致远
分类: 嵌入式
2013-07-03 19:44:46
//main.h
//====================================================================================
// The information contained herein is the exclusive property of
// Sunnnorth Technology Co. And shall not be distributed, reproduced,
// or disclosed in whole in part without prior written permission.
// (C) COPYRIGHT 2003 SUNNORTH TECHNOLOGY CO.
// ALL RIGHTS RESERVED
// The entire notice above must be reproduced on all authorized copies.
//====================================================================================
#ifndef _MAIN_H_
#define _MAIN_H_
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define RECV_SZIE 1024
#define SEND_SIZE 1024
int cut_list(char *bak[], char *buf, char *str);
void deal_with(int connfd, char *buf);
#endif
//main.h
//============================================================= |
//webserver.c
//=============================================================
// 语法格式: void deal_with(int connfd, char *buf)
// 实现功能: 处理客户端的请求
// 入口参数: conndf,buf
// 出口参数: 无
//=============================================================
#include "main.h"
#include <fcntl.h>
#include <sys/stat.h>
void deal_with(int connfd, char *buf)
{
char *resp_head = "HTTP/1.1 200 OK\r\n" \
"Content-Type: text/html\r\n" \
"Content-Length:%ld\r\n" \
"\r\n";
char *not_found = "HTTP/1.1 404 Not Found\r\n" \
"Content-Type: text/html\r\n" \
"Content-Length: 40\r\n" \
"\r\n" \
"File not found
";
char *bad_request = "HTTP/1.1 400 Bad Request\r\n" \
"Content-Type: text/html\r\n" \
"Content-Length: 39\r\n" \
"\r\n" \
"Bad Request (Invalid Hostname)
";
/* char *moved_permanently =
"HTTP/1.1 301 Moved Permanently\r\n"\
"Content-Length: 147\r\n" \
"Content-Type: text/html\r\n" \
"Location: %s\r\n" \
"\r\n" \
"Object
Moved
This document may be found here";
*/
char tmp_buf[SEND_SIZE] = {""};
char *tmp_bak[10];
char *first_line[5];
int fd;
FILE *fp;
struct stat file_buf;
int file_len = 0;
fp = fdopen(connfd, "w+"); //
cut_list(tmp_bak, buf, "\r\n");
cut_list(first_line, tmp_bak[0], " ");
if((first_line[0] != NULL) && (strcmp(first_line[0], "GET") == 0))
{
if(first_line[1] != NULL)
{
if(strcmp(first_line[1], "/") == 0)
{
strcat(first_line[1], "bai.htm");
}
first_line[1] = ++first_line[1];
if((fd = open(first_line[1], O_RDONLY)) == -1)
{
write(connfd, not_found, strlen(not_found));
perror("open index.html err!");
return ;
}
stat(first_line[1], &file_buf);
file_len = file_buf.st_size;
fprintf(fp, resp_head, file_len);
fflush(fp);
int len;
while((len = read(fd, tmp_buf, SEND_SIZE)) > 0)
{
write(connfd, tmp_buf, len);
memset(tmp_buf, 0, SEND_SIZE);
}
close(fd);
}
else
{
write(connfd, bad_request, strlen(bad_request));
}
}
return ;
}
/*************************************************************
*自己封装的字符串切割函数
*功 能:切割字符串
*************************************************************/
int cut_list(char *bak[], char *buf, char *str)