Hi,
Here is how to connect to Host
ort i.e.string Host = "
www.host.com"; int
Port = 80;
Note:
Socket is an int on unix type of systems but SOCKET on windows.
#define closesocket as close on unix type systems.
Do Connect. The code is pretty much cross platform (I have used it on linux
and lot's of unices as well as windows) You have to check your OS for the
headers to include though. On MS-Windows platforms you have to initialize
the stack (from the top of my head WSAStartup or somethig like that) and
during linktime you have include the appropriate library (I believe inet.lib
but just search for select on MSDN and scroll down). For Sun-os you also
have to add some libraries (just do a man -k select or something like that
to get the correct manual pages).
bool CBaseSocket::Init()
{
struct protoent *PE = getprotobyname( "tcp" );
if( PE ) ProtoNumber = PE->p_proto;
else ProtoNumber = 6; // Otherwise select proto anyway
struct hostent *pHE;
//memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_port = htons( Port );
// Try as dotted notation e.g. 192.168.1.1
sin.sin_addr.s_addr = inet_addr( Host.c_str() );
if( sin.sin_addr.s_addr != -1 )return true;
// Try as labels e.g. moonlit.xs4all.nl
if( ( pHE = gethostbyname( Host.c_str() ) ) == NULL )
{
LastError = string( "Couldn't get name" );
return false;
}
sin.sin_addr.s_addr = *reinterpret_cast<unsigned long*>(
*pHE->h_addr_list );
return true;
}
bool CBaseSocket::Connect()
{
bool RetVal = true;
if( !Init() )
{
LastError = string( "Couldn't convert address" );
Log << Level2 << LastError << End;
return false;
}
if( ( Socket = static_cast<SOCKET>( socket( AF_INET, SOCK_STREAM, 0 ) ) )
== INVALID_SOCKET )
{
LastError = string( "Error creating client Socket" );
Log << Level2 << LastError << End;
return false;
}
if( connect( Socket, (struct sockaddr*)&sin, sizeof( sin ) ) ==
SOCKET_ERROR )
{
LastError = string( "Couldn't connect to" );
Log << Level2 << LastError << End;
closesocket( Socket );
return false;
}
unsigned long True = 1;
ioctlsocket( Socket, FIONBIO, &True ); // Hope this works (undocumented)?
setsockopt( Socket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<char*>(
&True ), sizeof( True ) );
return true;
}
--
Regards, Ron AF Greve
http://moonlit.xs4all.nl