Created
October 5, 2014 13:54
-
-
Save ggaaooppeenngg/c049354c218d6357f4cb to your computer and use it in GitHub Desktop.
static server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <arpa/inet.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#define PORTNUM 2343 | |
#define SA struct sockaddr | |
char* HTTP = "HTTP/1.1 200 OK\r\n\ | |
Date: Sun, 05 Oct 2014 13:16:30 GMT\r\n\ | |
Server: Apache\r\n\ | |
Last-Modified: Tue, 03 Jul 2012 17:51:40 GMT\r\n\ | |
Content-Length: 43\r\n\ | |
Content-Type: text/html\r\n\r\n\ | |
<html><head><body>hihi</body></head></html>"; | |
char* head_boot = "HTTP/1.1 %s OK\r\n" | |
char* http_bootstrap = "Date: Sun, 05 Oct 2014 13:16:30 GMT\r\n\ | |
Server: Apache\r\n\ | |
Last-Modified: Tue, 03 Jul 2012 17:51:40 GMT\r\n\ | |
Content-Length: 43\r\n\ | |
Content-Type: text/html\r\n\r\n\ | |
<html><head><body>hihi</body></head></html>"; | |
int http_set_status_code(char* http_bootstrap,int status,int len); | |
int http_render(char* http_bootstrap ,int len); | |
int main(int argc, char *argv[]) | |
{ | |
struct sockaddr_in servaddr,cliaddr; | |
//设置服务器socket信息 | |
servaddr.sin_family = AF_INET; | |
socklen_t size = sizeof(struct sockaddr_in); | |
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
servaddr.sin_port = htons(PORTNUM); | |
int lisenfd = socket(AF_INET,SOCK_STREAM,0); | |
bind(lisenfd,(SA*)&servaddr,size); | |
listen(lisenfd,1); | |
int len = http_render(HTTP,strlen(HTTP)); | |
pid_t pid; | |
for(;;){ | |
int socket = accept(lisenfd,(SA *)&cliaddr,&size); | |
if((pid==fork())==0){ | |
//子进程接管socket,关闭listenfd,引用计数,并不是真正关闭socket | |
close(lisenfd); | |
send(socket,HTTP,strlen(HTTP),0); | |
close(socket); | |
exit(0); | |
} | |
//交给子进程处理,自己关闭socket | |
close(socket); | |
} | |
close(lisenfd); | |
} | |
int http_set_status_code(char* http_bootstrap,int status,int len){ | |
char* des = malloc(strlen(http_bootstrap)); | |
strcp(des,http_bootstrap); | |
char code [4]; | |
char* s = sprintf(des,iota(status,code,10)); | |
return s; | |
} | |
int http_render(char* http_bootstrap ,int len){ | |
return len; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment