1.练习 : 简单的Web服务器
1 #ifndef _HEAD_H_ 2 #define _HEAD_H_ 3 4 #include <stdio.h> 5 #include <string.h> 6 #include <stdlib.h> 7 #include <fcntl.h> 8 #include <sys/socket.h> 9 #include <arpa/inet.h> 10 #include <unistd.h> 11 12 #define MAX 1024 13 #define MAX_LISTEN 10 14 #define MAX_PATH 37 15 #define MAX_NAME 18 16 17 #define SER_IP "127.0.0.1" 18 #define SER_PORT 8000 19 #define ROOT "./www" 20 21 #define REPLY_HEAD "HTTP/1.1 200 OK Content-Type:" 22 #define TEXT "text/html" 23 //#define IMG "image/html" 24 #define IMG "jpg/html" 25 #define REPLY_END " " 26 27 void perror_exit(char *); 28 29 #endif//_HEAD_H_
1 //main.c 2 #include "head.h" 3 4 void perror_exit(char *str) 5 { 6 perror(str); 7 exit(1); 8 } 9 10 int main(int argc, char *argv[]) 11 { 12 int fd_socket = 0, opt = 1, err = 0, fd_ctl = 0, len = 0, fd_write; 13 struct sockaddr_in serve_addr; 14 char buf[MAX] = {0}; 15 char *start = NULL, *end = NULL, *type = NULL, *filename = NULL; 16 char *asgv[2] = {0}; 17 18 fd_socket = socket(AF_INET, SOCK_STREAM, 0); 19 20 bzero(&serve_addr, sizeof(serve_addr)); 21 serve_addr.sin_family = AF_INET; 22 serve_addr.sin_port = htons(SER_PORT); 23 inet_pton(AF_INET, SER_IP, &serve_addr.sin_addr.s_addr); 24 25 err = setsockopt(fd_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); 26 if(-1 == err) { 27 perror_exit("setsockopt"); 28 } 29 err = bind(fd_socket, (struct sockaddr *)&serve_addr, sizeof(serve_addr)); 30 if(-1 == err) { 31 perror_exit("bind"); 32 } 33 err = listen(fd_socket, MAX_LISTEN); 34 if(-1 == err) { 35 perror_exit("listen"); 36 } 37 38 while(1) 39 { 40 char path[MAX_PATH] = {0}; 41 42 bzero(buf, sizeof(buf)); 43 len = 0; 44 //fd_ctl = accept(fd_socket, &serve_addr, sizeof(serve_addr)); 45 fd_ctl = accept(fd_socket, NULL, NULL); 46 if(-1 == fd_ctl) { 47 perror_exit("accept"); 48 } 49 len = read(fd_ctl, buf, MAX); 50 if(-1 == len) { 51 perror_exit("read"); 52 } 53 buf[len] = '