#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
int socketfd, newsocket;
char *filename;
void shutup (int signal)
{
times ();
printf ("Shutting down...\n\n"); close (newsocket);
close (socketfd);
}
int times ()
{
struct tm *ahora;
char buffer [40];
strftime (buffer
, 40, "%d/%m/%Y %H:%M:%S" , ahora
); return 0;
}
int main (int argc, char *argv [])
{
struct tm *ahora;
char hora [40];
strftime (hora
, 40, "%d/%m/%Y %H:%M:%S" , ahora
); printf ("SmallServ 2.0 - By Sagrini - Sagrini 2010 - %s\n", hora
);
if (getuid()!=0)
{
printf ("This proccess must be run by root.\n\n"); return 1;
}
if (argc<3)
{
printf ("Use: %s <PORT> <LOG> [MODE]\nMode:\t\t0) Fork the proccess to background [DEFAULT].\n\t\t1) Run in the terminal.\n\n", argv
[0]); return 1;
}
int cont;
struct sockaddr_in client, host;
char buffer [1024];
int size=sizeof (client);
filename = argv [2];
socketfd=socket (2, 1 , 0);
host.sin_family=AF_INET;
host.
sin_port=htons
(atoi (argv
[1])); host.sin_addr.s_addr=0;
bind (socketfd, (struct sockaddr*)&host, sizeof (struct sockaddr));
listen (socketfd, 3);
times ();
if (argv
[3] != NULL
&& atoi (argv
[3]) == 1) printf ("\nStarting up...\n\n");
signal (SIGTERM, shutup);
signal (SIGINT, shutup);
if (argv
[3] == NULL
|| atoi (argv
[3]) == 0) daemon (1, 0);
while (1)
{
newsocket=accept (socketfd, (struct sockaddr*)&client, &size);
times ();
printf ("Got connection from %s:%d\n", inet_ntoa
(client.
sin_addr), ntohs
(client.
sin_port)); fprintf (log, "Got connection from %s:%d\n", inet_ntoa
(client.
sin_addr), ntohs
(client.
sin_port));
cont=recv (newsocket, &buffer, 1024, 0);
while (cont>2)
{
times ();
buffer [cont-1]='\0';
printf ("RECV %d bytes: %s ", cont
-2, buffer
); fprintf (log, "RECV %d bytes: %s\n", cont
-2, buffer
);
cont=recv (newsocket, &buffer, 1024, 0);
}
times ();
printf ("Finishing connection from %s:%d\n\n", inet_ntoa
(client.
sin_addr), ntohs
(client.
sin_port)); fprintf (log, "Finishing connection from %s:%d\n\n", inet_ntoa
(client.
sin_addr), ntohs
(client.
sin_port)); close (newsocket);
}
close (socketfd);
return 0;
}
Si alguien cree que algo se puede mejorar, que postee xD