#if defined WIN32
#include <winsock.h>
#else
#define closesocket close
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define BUFFERSIZE 255
#define PROTOPORT 27015
#define QLEN 10
void ErrorHandler(char *errorMessage) {
perror(errorMessage);
}
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
int main(int argc, char *argv[]) {
int port;
if (argc > 1) {
port = atoi(argv[1]);
} else {
port = PROTOPORT;
if (port<0) {
printf("bad port number %s \n", argv[1]);
return 0;
}
}
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2 ,2), &wsaData);
if (iResult != 0){
printf ("error at WSASturtup\n");
return 0;
} else {
printf("WSAStartup eseguita\n");
}
#endif
//Creazione Socket
int Mysocket;
Mysocket=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Mysocket < 0) {
ErrorHandler("socket creation failed.\n");
ClearWinSock();
return 0;
} else {
printf("socket inizializzata con successo\n");
}
struct sockaddr_in sad;
memset(&sad, 0, sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr( "127.0.0.1" );
sad.sin_port = htons(port);
//Bind
if (bind(Mysocket, (struct sockaddr*) &sad, sizeof(sad)) <0) {
ErrorHandler("bind() failed.\n");
closesocket(Mysocket);
ClearWinSock();
return 0;
}
//LISTEN
if (listen (Mysocket, QLEN) <0) {
ErrorHandler("listen() failed.\n");
closesocket(Mysocket);
ClearWinSock();
return 0;
}
struct sockaddr_in cad;
// int Rsocket; //socket remota che comunica con il client
int clientSocket;
int clientLen; //dimensione del indirizzo client
char buf[BUFFERSIZE];
printf( "In attesa di un client con cui comunicare...\n\n");
//Loop Infinito
while (1) {
memset(&cad, 0, sizeof(cad));
memset(buf, 0, sizeof(buf));
clientLen = sizeof(cad);
//ACCEPT
if ( (clientSocket = accept(Mysocket, (struct sockaddr *)&cad, &clientLen)) < 0) {
printf("accept() failed.\n");
closesocket(Mysocket);
ClearWinSock();
return 0;
} else {
printf("connesione accettata\n");
}
}
closesocket(Mysocket);
#if defined WIN32
WSACleanup();
#endif
return EXIT_SUCCESS;
}