#include #include #include #include #include #include #include #include #include #include #define WPORT 8008 /* really simple web server that binds to port WPORT It simply reads from a local file and pumps it over the socket */ void service(int cfd) // called by main server loop { int ffd; // local file descriptor int n; // bytes read char buf[1024]; char buf1[512]; char buf2[128]; char page[128]; // filename of page // parse request n = read(cfd,buf1,511); buf1[n]=0; // 0-terminate string (just to be sure!) sscanf(buf1,"GET /home/%s %s\n",page,buf2); printf("page is %s\n",page); // open local file ffd = open(page,O_RDONLY,0); if (ffd<0) ffd = open("index.html",O_RDONLY,0); // default // send OK sprintf(buf,"HTTP/1.1 200 OK\n"); write(cfd,buf,strlen(buf)+1); n = 1024; while(n>0) { n = read(ffd,buf,1024); if (n>0) write(cfd,buf,n); } close(ffd); close(cfd); } // service int main(int argc, char** argv) { int sfd, cfd; // server and communication sockets int n, len; struct sockaddr_in saddr; // used locally by bind struct sockaddr_in caddr; // info about a client saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); // allow any interface saddr.sin_port = htons(WPORT); len = sizeof(saddr); // steps to create the server (listening) socket sfd = socket(AF_INET,SOCK_STREAM,0); n = 1; setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(int)); bind(sfd,(struct sockaddr*)&saddr,len); listen(sfd,16); // sets # of clients that can be queued len = sizeof(caddr); for(;;) { // wait for client connection, // create communication socket (cfd), // and record client info in caddr cfd = accept(sfd,(struct sockaddr*)&caddr,&len); if (cfd<1) exit(1); printf("connection from %s\n", inet_ntoa(caddr.sin_addr)); service(cfd); close(cfd); } // server loop exit(0); }