//server
#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>
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
int main(void) {
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2 ,2), &wsaData);
if (iResult != 0){
printf ("error at WSASturtup\n");
return 0;
}
#endif
// CREAZIONE DELLA SOCKET
int Mysocket;
Mysocket= socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Mysocket < 0) {
printf(" creazione socket fallita \n");
return 0;
}
// ASSEGNAZIONE DI UN INDIRIZZO ALLA SOCKET
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(45890);
if (bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
ErrorHandler("bind() failed.\n");
closesocket(MySocket);
ClearWinSock();
return 0;
}
// SETTAGGIO DELLA SOCKET ALL'ASCOLTO
int qlen=10;
if (listen (Mysocket, qlen) <0) {
printf("listen() failed.\n");
closesocket(Mysocket);
return 0;
}
// ACCETTARE UNA NUOVA CONNESSIONE
struct sockaddr_in cad;
int clientSocket;
int clientLen;
printf("in attesa di connessione \n");
while (1) {
clientLen = sizeof(cad);
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,&clientLen)) < 0){
ErrorHandler("accept() failed.\n");
// CHIUSURA DELLA CONNESSIONE
closesocket(MySocket);
ClearWinSock();
return 0;
}
}
}
----------------------------------------------------------------------------
client
#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>
#define BUFFERSIZE 512
void ErrorHandler(char *errorMessage) {
printf(errorMessage);
}
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
int main(void) {
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2 ,2), &wsaData);
if (iResult != 0){
printf ("error at WSASturtup\n");
return 0;
}
#endif
// CREAZIONE DELLA SOCKET
int Csocket;
Csocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Csocket < 0) {
ErrorHandler("socket creation failed.\n");
closesocket(Csocket);
ClearWinSock();
return 0;
}
// COSTRUZIONE DELL’INDIRIZZO DEL SERVER
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( 45890 );
// CONNESSIONE AL SERVER
if (connect(Csocket, (struct sockaddr *)&sad, sizeof(sad)) < 0)
{
ErrorHandler( "Failed to connect.\n" );
closesocket(Csocket);
ClearWinSock();
return 0;
}
// CHIUSURA DELLA CONNESSIONE
closesocket(Csocket);
ClearWinSock();
printf("\n");
system("pause");
return(0);
}