Servidor web sencillo en C bajo Linux

julio 26 20092 comentarios

Guardado en : General, Software Libre

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
unsigned short port = 8000; //N煤mero de puerto predeterminado del servidor
 
#define DEBUG 1
 
char * error_return = "<HTML>\n<BODY>Archivo no encontrado\n</BODY>\n</HTML>";
char ret_buf[32768];
char * read_file(char * buf, int num_buf){
	int i;
	char *cp, *cp2;
	FILE *f;
	cp = buf + 5;
	cp2 = strstr(cp, " HTTP");
	if(cp2 != NULL) *cp2 = '\0';
	if(DEBUG) printf("file: |%s|\n",cp);
	//fetch file:
	f = fopen(cp, "r");
	if(f == NULL) return error_return;
	i = fread(ret_buf,1,32768,f);
	if(i == 0){fclose(f); return error_return;}
	ret_buf[i] = '\0';
	fclose(f);
	return ret_buf;
}
 
int main(int argc, char* argv[]){
	int i, sock;
	char* recvBuffer = (char *)malloc(4001);
	int rc = 0;
	int serversocket;
	struct sockaddr_in serverAddr;
	struct sockaddr_in clientAddr;
	int clientAddrSize;
	struct hostent* entity;
	int totalReceived;
	int size;
	int totalSent;
	int bytesSent;
	char * cbuf;
	serversocket = socket(AF_INET, SOCK_STREAM, 0);
	if(serversocket == -1){
		printf("Socket inv谩lido\n");
		exit(1);
	}
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(port);
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	memset(&(serverAddr.sin_zero),0,8);
	printf("Uni贸n del socket de servidor con el puerto %d\n",port);
	rc = bind(serversocket, (struct sockaddr*) &serverAddr, sizeof(struct 
sockaddr));
	if(rc == -1){
		printf("Bad bind\n");
		exit(1);
	}
	rc = listen(serversocket, 10);//permite 10 peticiones en cola
	if(rc == -1){
		printf("Bad listen\n");
		exit(1);
	}
	printf("Aceptando conexiones ...\n");
	while(1){
		clientAddrSize = sizeof(struct sockaddr_in);
		do
			sock = accept(serversocket,(struct sockaddr*) &clientAddr,
					&clientAddrSize);
		while((sock == -1) && (errno == EINTR));
		if(sock == -1){
			printf("Mala Aceptaci贸n\n");
			exit(1);
		}
		entity = gethostbyaddr((char *) &clientAddr.sin_addr,sizeof(struct 
in_addr),
					AF_INET);
		if(DEBUG) printf("Conexi贸n desde %s\n",inet_ntoa((struct in_addr)clientAddr.sin_addr));
		i = recv(sock, recvBuffer,4000,0);
		if(i == -1) break;
		if(recvBuffer[i-1] != '\n') break;
		recvBuffer[i] = '\0';
		if(DEBUG){
			printf("Recibido del cliente: %s\n",recvBuffer);
		}
		//llama a una funci贸n de trabajo separada para procesar la petici贸n:
		cbuf = read_file(recvBuffer, totalReceived);
		size = strlen(cbuf);
		totalSent = 0;
		do{
			bytesSent = send(sock,cbuf + totalSent,strlen(cbuf + totalSent),0);
			if(bytesSent == -1) break;
			totalSent += bytesSent;
		}while(totalSent < size);
		if(DEBUG) printf("Conexi贸n cerrada por el cliente.\n");
		close(sock);
	}
	return 0;
}
Comparte esta informaci贸n:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • BarraPunto
  • LinkedIn
  • Technorati
  • TwitThis

Quiz谩 te interese :

Acerca del autor: Daniel

2 Respuestas a “Servidor web sencillo en C bajo Linux”

  1. pitogrillo dice:

    Debe ser una confusi贸n, pues 茅sto es un cliente, jeje

  2. Daniel dice:

    Corregido, (como se agregar贸n los dos seguidos cliente y servidor me equivoqu茅), gracias por tu comentario!

    ?

Deja un comentario


Licencia y uso

Las técnicas demostradas en los tutoriales pueden ser utilizadas sin ninguna limitación y tampoco es obligatorio dar una atribución.


Los textos, imágenes y tutoriales son propiedad de sus respectivos autores, nuestro contenido se encuentra bajo licencia Creative Commons Share-Alike.

Escribe algo para el sitio

El escribir un tutorial o un artículo, mandarnos un enlace para Ubicuos, no solamente es una forma de obtener publicidad, si no también de dar algo a la comunidad y nosotros te lo recompensamos con los premios del mes! Leer más de nuestras promociones

驴Sugerencias?

Este es TU sitio, si tienes sugerencias o ideas de c贸mo podemos mejorarlo para ti, 隆Por favor h谩znoslos saber!

Hacemos nuestro mayor esfuerzo en proporcionar un sitio 煤til y amigable y esperamos que disfrutes tu tiempo aqu铆.

Ayuda a Difundir

Te gusta Ubicuos?

Ve las formas en que nos puedes apoyar.

Apoyando a Ubicuos.com

Submit your linkClose