Questo è il template (assolutamente portabile, a differenza delle funzioni pure di Winsock o dell'uso di MFC) che uso per i server, l'unica cosa da cambiare è la funzione LANCIA_UN_THREAD e il fatto di usare dei metodi (dipendenti dal sistema) per ricevere segnalazioni di fine del programma (altrimenti dal loop non esci mai)
codice:
#define SERVERPORT 10202 /* la porta TCP da usare */
#define MAX_CONN_PENDING 5 /* max connessioni in attesa del server */
void main ()
{
int sfd, tfd;
int i;
struct sockaddr_in sa, isa;
struct hostent *hp;
/* chiede l'indirizzo del local host */
gethostname(localhost,MAXHOSTNAME);
if ((hp=gethostbyname(localhost))==NULL) {
perror("Impossibile ottenere nome host locale\n");
exit(1);
}
/* inserisce il socket number dentro la struttura del socket */
sa.sin_port=htons((short int) SERVERPORT);
/* costruisce la struttura che contiene l'indirizzo del local host */
memcpy(&sa.sin_addr, hp->h_addr, hp->h_length);
sa.sin_family=hp->h_addrtype;
/* richiede un descrittore di socket */
if (( sfd=socket(hp->h_addrtype, SOCK_STREAM, 0))<0 ) {
perror ("errore apertura socket \n");
exit(1);
}
/* fa il bind alla service port */
if (bind(sfd,(struct sockaddr*) &sa, sizeof (sa))<0) {
perror("bind rifiutato\n");
exit(1);
}
/* massimo numero di connessioni accettate */
listen(sfd, MAX_CONN_PENDING);
/* SERVER LOOP */
while (1)
{
i=sizeof (isa);
if (( tfd=accept(sfd,(struct sockaddr*) &isa, &i))<0) {
perror("errore accept \n");
exit(1);
/* in tfd ho il file descriptor della connessione */
LANCIA_UN_THREAD_PER_ESEGUIRE_LA_RICHIESTA(tfd);
}
}
Ah, in windows devi includere solo l'header <windows.h> e <winsock2.h>
inoltre devi sempre scrivere nella main, prima di richiamare qualunque funzione socket, il seguente codice (copiato e incollato da MSDN
codice:
#ifdef WIN32
//code from MSDN
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("Necessaria versione 2 di winsock\n");
return ;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("Necessaria versione 2 di winsock\n");
WSACleanup( );
return ;
}
#endif