Faculdade de Informática da PUCRS
Prof. Márcio Serolli Pinho - [email protected]
Funções de Conexão via Sockets
Para utilizar estas funções você deve incluir o header "winsock.h" no seu
fonte e a biblioteca "libwsock32.a" no seu projeto.
// ***********************************************
// ConnectToTheServerIP ( char *serverName, unsigned short portNum )
//
// Conecta com uma Máquina de nome "serverName",
// através da porta "portNum"
//
// Esta função devolve uma estrutura do tipo SOCKET
// que deverá ser usada nas demais funções de
// transmissão/recepção via sockets
//
// ***********************************************
SOCKET ConnectToTheServerIP ( char *serverName, unsigned short portNum )
{
char myName[265];
HOSTENT *hostent;
WSAData info;
SOCKET clientSocket;
SOCKADDR_IN socketAddr;
WORD socketVersion = MAKEWORD ( 1, 1 );
// Setup the socket library version.
if ( WSAStartup ( socketVersion, &info ) == SOCKET_ERROR ) {
printf ( "Couldn't initialize the socket library.\n" );
exit (1);
}
// Check the library version.
if ( info.wVersion != socketVersion ) {
fprintf ( stderr, "Couldn't initialize the socket library.\n" );
exit (1);
}
// clear the address struct.
memset ( &socketAddr, 0, sizeof ( struct sockaddr_in ) );
int result = gethostname ( myName, sizeof ( myName ) );
if ( result == WSANOTINITIALISED )
printf ( "Socket library wasn't correctly initialized.\n" );
// Check our own address.
hostent = gethostbyname ( serverName );
if ( hostent == NULL )
return INVALID_SOCKET;
memset ( &socketAddr, 0, sizeof ( socketAddr ) );
memcpy ( (char *)&socketAddr.sin_addr, hostent->h_addr, hostent->h_length );
socketAddr.sin_family = AF_INET;
socketAddr.sin_addr = *((LPIN_ADDR)*hostent ->h_addr_list);
socketAddr.sin_port = htons ( portNum );
// Create the client socket.
clientSocket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( clientSocket == INVALID_SOCKET )
return INVALID_SOCKET;
// Connect to the server.
if ( connect (
clientSocket, ( struct sockaddr * )&socketAddr, sizeof ( socketAddr
) ) == SOCKET_ERROR ) {
closesocket ( clientSocket );
return INVALID_SOCKET;
}
return clientSocket;
}
// ***********************************************
// SendMessageIP ( SOCKET sock, char *buf, int numBytes )
//
// Esta função permite enviar uma sequencia de
// "numBytes" através do SOCKET "sock". Os dados
// a serem enviados devem estar na variável "buf"
//
// ***********************************************
void SendMessageIP ( SOCKET sock, char *buf, int numBytes ) {
int result = send ( sock, buf, numBytes, 0 );
}
// ***********************************************
// void ReceiveMessageIP ( SOCKET sock, char *buf, int numBytes )
//
// Esta função recebe "numBytes" através do
// SOCKET "sock". Os dados recebido são armazenados
// no vetor "buf"
//
// ***********************************************
void ReceiveMessageIP ( SOCKET sock, char *buf, int numBytes ) {
memset ( buf, 0, numBytes );
int result = recv ( sock, buf, numBytes, 0 );
if ( result == SOCKET_ERROR ) {
printf ( "Error reading socket number %d\n", sock );
exit (1);
}
}
// ***********************************************
// BOOL IsThereAMsg ( SOCKET sock )
//
// Esta função informa se há um dados disponível
// no Socket "sock"
//
// ***********************************************
BOOL IsThereAMsg ( SOCKET sock ) {
fd_set socketSet;
const struct timeval FAR timeout = { 0, 0 };
int result;
FD_ZERO ( &socketSet );
FD_SET ( sock, &socketSet );
result = select ( 1, &socketSet, NULL, NULL, &timeout );
if ( FD_ISSET ( sock, &socketSet ) )
return true;
return false;
}
// ***********************************************
// SOCKET CreateServerIP ( unsigned short portNum )
//
// Esta função cria um servidor que "atenderá"
// através da porta "portNum"
//
//
// ***********************************************
SOCKET CreateServerIP ( unsigned short portNum ) {
char myName[265];
HOSTENT *hostent;
WSAData info;
SOCKET serverSocket;
SOCKADDR_IN socketAddr;
WORD socketVersion = MAKEWORD ( 1, 1 );
// Setup the socket library version.
if ( WSAStartup ( socketVersion, &info ) == SOCKET_ERROR ) {
printf ( "Couldn't initialize the socket library.\n" );
exit (1);
}
// Check the library version.
if ( info.wVersion != socketVersion ) {
fprintf ( stderr, "Couldn't initialize the socket library.\n" );
exit (1);
}
// clear the address struct.
memset ( &socketAddr, 0, sizeof ( struct sockaddr_in ) );
int result = gethostname ( myName, sizeof ( myName ) );
if ( result == WSANOTINITIALISED )
printf ( "Socket library wasn't correctly initialized.\n" );
// Check our own address.
hostent = gethostbyname ( myName );
if ( hostent == NULL )
return INVALID_SOCKET;
// Create the socket.
serverSocket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( serverSocket == INVALID_SOCKET )
return INVALID_SOCKET;
socketAddr.sin_family = hostent->h_addrtype;
socketAddr.sin_port = htons ( portNum );
// Bind the socket.
if ( bind (
serverSocket, ( struct sockaddr * )&socketAddr, sizeof ( struct
sockaddr_in ) ) == SOCKET_ERROR ) {
closesocket ( serverSocket );
return INVALID_SOCKET;
}
listen ( serverSocket, SOMAXCONN );
printf ( "TCP/IP Server created at port %d.\n", portNum );
return serverSocket;
}
// ***********************************************
// SOCKET AcceptNewClientIP ( SOCKET serverSocket, SOCKET &newSocket )
//
// Esta função recebe um novo cliente do
// servidor "serverSocket" e devolve no
// segundo parâmetro o socket do
// cliente que conectou
// ***********************************************
int AcceptNewClientIP ( SOCKET serverSocket, SOCKET &newSocket )
{
newSocket = accept ( serverSocket, NULL, NULL );
if ( newSocket == INVALID_SOCKET ) {
fprintf ( stderr, "Error waiting for new connection!\n" );
closesocket ( serverSocket );
return 0;
}
printf ( "New client received !\n" );
return 1;
}
// ***********************************************
// int CheckNewClient(serverSocketIP)
//
// verifica se existe um novo cliente para o
// servidor
//
// ***********************************************
int CheckNewClient(serverSocketIP)
{
SOCKET S;
if ( IsThereAMsg ( serverSocketIP ) )
{
ret = AcceptNewClientIP ( serverSocketIP, S );
if (ret)
{
// Aqui o socket "S" do novo cliente deve ser armazenado
return 1;
}
}
return 0;
}
// ***********************************************
// CloseSocket(SOCKET clientSock)
//
//
// ***********************************************
void CloseSocket(SOCKET clientSock)
{
closesocket(clientsock);
}
FIM