home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
GianuzziV
/
SO1
/
TCPtimeserver.c
< prev
next >
Wrap
C/C++ Source or Header
|
2005-04-03
|
3KB
|
100 lines
/**********************************************************************************
* Programma: TCPtimeserver.c *
* *
* finalita': Restituisce il valore di time ai processi che si connettono *
* il client e' TCPtimeclient.c, il protocollo e' TCP. *
* *
* Sintassi: TCPtimeserver [ port number ] *
* port - port number da abilitare *
* Il port number e' opzionale, se non passato si usa SERVER_PORT *
* *
***********************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <stdio.h>
#include <netdb.h>
#define SERVER_PORT 3123
#define QLEN 5 // lunghezza coda accept
#define MAXHOSTNAME 100
#define SIZE 1024
char buf[SIZE];
int main(int argc, char *argv[])
{
int sockfd, client_sockfd;
int nread, port, len, i;
struct sockaddr_in serv_addr, client_addr;
time_t t;
char localhost[MAXHOSTNAME+1];
struct hostent *hp;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror(NULL);
exit(2);
}
// trovo il nome DNS dell'host
gethostname(localhost,MAXHOSTNAME);
// trovo la struttura hostent dell'host
// ATTENZIONE, non usare gethostid!!!
if ((hp=gethostbyname(localhost))==NULL) {
printf("server: errore local host \n");
exit(1);
}
// assegna l'indirizzo locale per il bind
memset((char *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
/* costruisce la struttura che contiene l'indirizzo del local host */
bcopy((char *) hp->h_addr, (char *) &serv_addr.sin_addr, hp->h_length);
// Controlla gli argomenti passati nella command-line (port)
if (argc > 1) port = atoi (argv[1]); // converte in binario
else port = SERVER_PORT; // default port number
serv_addr.sin_port = htons((u_short)port);
// associa un indirizzo locale al socket
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof (serv_addr)) < 0) {
perror(NULL);
exit(1);
}
// lunghezza coda accept
if (listen(sockfd, QLEN) < 0) {
perror(NULL);
exit(1);
}
len=sizeof (client_addr);
printf("server prima di accept port %d IP %s\n", ntohs(serv_addr.sin_port), inet_ntoa(serv_addr.sin_addr));
for (;;) {
client_sockfd = accept(sockfd, &client_addr, &len);
if (client_sockfd <= 0)
{
perror (NULL);
exit(1);
}
time(&t);
sprintf(buf, "%s", asctime(localtime(&t)));
len = strlen(buf) + 1;
write(client_sockfd, buf, len);
close(client_sockfd);
}
}