I am writing a class for TCP/IP Network client communication. In the class header I create a SOCKET member. The class also contains a method for calling WSAStartup and checking the version. The method to make a connection first calls WSAStartup and then initialises the SOCKET member calling the socket() function. See code below. I am wondering if this is "correct", or if there is a better way.
The header file:
/*network.h*/
public class IPnetwork
{
private:
WSADATA wsaData ;
SOCKET hSocket ;
sockaddr_in socketAddress ;
static const int SERVER_PORT = 502 ;
unsigned long int = serverIP ;
public:
IPnetwork(char* serverIPaddress) ;
bool Connect() ;
bool Disconnect() ;
~IPnetwork() ;
private:
bool startWinSock() ;
} ;
The source code:
/*network.cpp*/
IPnetwork::IPnetwork(char* serverIPaddress)
{
serverIP = inet_addr(serverIPaddress) ;
}
bool IPnetwork::Connect()
{
/* start winsock */
if(!startWinSock())
{
return false ; /* winsock problem */
}
/* Create socket */
if ((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
return false ; /* could not create socket */
}
/* fill socket address structure */
socketAddress.sin_family = AFINET ;
socketAddress.sin_port = htons(SERVER_PORT) ;
socketAddress.sin_addr.S_un.S_addr = serverIP ;
/* connect */
if(connect(hSocket,reinterpret_cast<sockaddr*>(&socketAddress), sizeof(sockAddr))!=0)
{
return false ; /* could not connect*/
}
return true ;
}
bool IPnetwork::startWinSock()
{
if(WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0),&wsaData)==0)
{
/* Check if major version is at least REQ_WINSOCK_VER */
if (LOBYTE(wsaData.wVersion) < REQ_WINSOCK_VER)
{
return false ; /* winsock started but version is too low */
}
else
{
return true ; /* winsock started with right version*/
}
}
else
{
return false ; /* winsock not started */
}
}
You're worried about defining a variable of type SOCKET
, and when its constructor runs?
That's not a problem, since SOCKET
is a C-compatible plain-old-data integral type that holds a socket identifier. It isn't an object. There's no non-trivial construction or destruction associated with the variable itself.