Sockets: um mini webserver

Publicado por Andre Luiz da Silva 16/05/2004

[ Hits: 10.615 ]

Homepage: http://localhost

Download mini_apache.c




Em mais uma empreitada sobre sockets, resolvi "enfeitar" um pouco e trazer um exemplo do que de longe poderia ser chamado de webserver, ou melhor, de mini webserver, ou talvez um micro webserver, honestamente falando podemos chamá-lo de nano webserver... o funcionamento eh clássico, tu põe ele pra rodar e ele ficará ouvindo na porta 8080, ou  se fosse for root o suficiente pode alterar a constante PORT e colocá-lo pra rodar na porta 80, como se é de contume em servidores web...

  



Esconder código-fonte

/********************************************************************************* 
 * Author: Andre Luiz da Silva                      
 * Date: 16/05/2004                        
 * Obs: Nao se esqueca de colocar um arquivinho "index.html" com algumas tags em html no mesmo
*            diretório onde inicio o programa... beleza?! 
 *********************************************************************************       * This program is free software; you can redistribute it and/or modify it under 
 * the terms of the GNU General Public License as published by the Free     
 * Software Foundation; either version 2 of the License, or (at your option)     
 * any later version.                         
 *                                
 * This program is distributed in the hope that it will be useful, but WITHOUT   
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or         
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for     
 * more details.                         
 *********************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/sendfile.h>

#define PORT 8080
#define BACKLOG 10
#define INDEX_PATH "index.html"

int DoDaemon()
{
   pid_t child_pid;

   child_pid = fork();
   if (!child_pid)
   {
      int i;
      for (i = 0; i < getdtablesize(); ++i)
         close (i);
      setsid();
      return 0;
   }
   if (child_pid > 0)
      exit (0);
   else
      return -1;
}

int send_file(int fd_out)
{
   int fd_in;
   struct stat fd_in_stat;

   if ((fd_in = open(INDEX_PATH, O_RDONLY)) == -1)
   {
      perror ("open(): ");
      exit (1);
   }
   if ((stat (INDEX_PATH, &fd_in_stat)) == -1)
   {
      perror ("stat(): ");
      exit (1);
   }
   sendfile (fd_out, fd_in, 0, fd_in_stat.st_size);
   close (fd_in);

   return 0;
}
   
int main(int argc, char **argv)
{
   struct sockaddr_in server;
   int port = PORT, server_sd, remote_sd;

   memset (&server, 0, sizeof(server));
   server.sin_port = htons (port);
   server.sin_family = AF_INET;
   
   if ((DoDaemon()) == -1)
      exit (1);

   if ((server_sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
   {
      perror ("socket(): ");
      exit (1);
   }
   if ((bind (server_sd, (struct sockaddr *)&server, sizeof(server))) == -1)
   {
      perror ("bind(): ");
      exit (1);
   }

   listen (server_sd, BACKLOG);
   strcpy (argv[0], "mini-apache: esperando por conexões...");
   
   while (1)
   {
      remote_sd = accept (server_sd, NULL, NULL);
      send_file (remote_sd);
      close (remote_sd);
   }
   
   close (server_sd);
   return 0;
}

Scripts recomendados

Fractal

Descritor de protocolo

Simples TCP SERVER em C#

Socket em C/C++ - SERVER

Mostrar IP em C#


  

Comentários
[1] Comentário enviado por y2h4ck em 17/05/2004 - 10:46h

ficou da hora seu exemplo :)

[2] Comentário enviado por andrack em 17/05/2004 - 23:59h

valew kra.... 8^)

[3] Comentário enviado por DarthVictor em 12/06/2011 - 18:07h

Nossa, eu adorei.... Muito bom o exemplo....


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts