Discussione: Socket&C++
View Single Post
Old 11-04-2004, 15:34   #7
Luc@s
Senior Member
 
L'Avatar di Luc@s
 
Iscritto dal: Apr 2002
Cittā: Vigevano(PV)
Messaggi: 2123
risolto:
Codice:
/**
* A Sock Client Func
*/
#ifndef CLIENT_H
#define CLIENT_H

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

/** Chiude */
void ChiudiSocket(int sock) 
{
	close (sock);
	return;
}

/** Crea */
int CreaSocket(char* Destinazione, int Porta) 
{
	struct sockaddr_in temp;
	struct hostent *h;
	int il_socket;
	int errore;
	
	temp.sin_family=AF_INET;
	temp.sin_port=htons(Porta);
	h=gethostbyname(Destinazione);
	if (h==0)
	{
		printf("Connessione IP alfanumerico... fallito!\n");
		exit(1);
	}
	bcopy(h->h_addr,&temp.sin_addr,h->h_length);
	il_socket=socket(AF_INET,SOCK_STREAM,0);
	errore=connect(il_socket,(struct sockaddr*) &temp, sizeof(temp));
	return il_socket;
}
/** Spedisce */
void SpedisciMessaggio (int sock, char* Messaggio) 
{
	prinft("%s\n", Messaggio);
	if (write(sock,Messaggio,strlen(Messaggio))<0) 
	{
		prinft("Impossibile comunicare col server\n");
		ChiudiSocket(sock);
		exit(1);
	}
	printf("Messaggio inviato!\n");
	return;
}

#endif

/**
* A Sock Server Func
*/
#ifndef SERVER_H
#define SERVER_H

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>

/** Crea */
int CreaServerSocket(int Porta) 
{
	int il_socket,errore;
	struct sockaddr_in temp;
	
	il_socket=socket(AF_INET,SOCK_STREAM,0);
	temp.sin_family=AF_INET;
	temp.sin_addr.s_addr=INADDR_ANY;
	temp.sin_port=htons(Porta);
	
	errore=fcntl(il_socket,F_SETFL,O_NONBLOCK);
	
	errore=bind(il_socket,(struct sockaddr*) &temp,sizeof(temp));
	errore=listen(il_socket,7);
	
	return il_socket;
}
/** Chiude */
void ChiudiServerSocket(int sock) 
{
	close(sock);
	return;
}

#endif
__________________
Gnu/Linux User
Luc@s č offline   Rispondi citando il messaggio o parte di esso