NewNet/nntcpclientsocket.cpp

00001 /*  NewNet - A networking framework in C++
00002     Copyright (C) 2006 Ingmar K. Steen (iksteen@gmail.com)
00003 
00004     This program is free software; you can redistribute it and/or modify
00005     it under the terms of the GNU General Public License as published by
00006     the Free Software Foundation; either version 2 of the License, or
00007     (at your option) any later version.
00008 
00009     This program is distributed in the hope that it will be useful,
00010     but WITHOUT ANY WARRANTY; without even the implied warranty of
00011     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012     GNU General Public License for more details.
00013 
00014     You should have received a copy of the GNU General Public License
00015     along with this program; if not, write to the Free Software
00016     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00017 
00018  */
00019 
00020 #include "nntcpclientsocket.h"
00021 #include "nnlog.h"
00022 #include "platform.h"
00023 #include "util.h"
00024 #include <iostream>
00025 
00026 void
00027 NewNet::TcpClientSocket::connect(const std::string & host, unsigned int port)
00028 {
00029   // FIXME: Make the TcpClientSocket class a bit more functional
00030   assert((descriptor() == -1) || (socketState() == SocketUninitialized));
00031 
00032   setSocketState(SocketConnecting);
00033 
00034   NNLOG("newnet.net.debug", "Resolving host '%s'.", host.c_str());
00035   struct hostent *h = gethostbyname(host.c_str());
00036   if(! h)
00037   {
00038     NNLOG("newnet.net.warn", "Cannot resolve host '%s'.", host.c_str());
00039     setSocketError(ErrorCannotResolve);
00040     cannotConnectEvent(this);
00041     return;
00042   }
00043 
00044   struct sockaddr_in address;
00045   memset(&address, 0, sizeof(address));
00046   address.sin_family = AF_INET;
00047   memcpy(&(address.sin_addr.s_addr), *(h->h_addr_list), sizeof(address.sin_addr.s_addr));
00048   address.sin_port = htons(port);
00049 
00050   NNLOG("newnet.net.debug", "Connecting to host '%s:%u'.", host.c_str(), port);
00051 
00052   int s = socket(PF_INET, SOCK_STREAM, 0);
00053   setnonblocking(s);
00054   setDescriptor(s);
00055 
00056   if(::connect(s, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) == 0)
00057   {
00058     NNLOG("newnet.net.debug", "Connected to host '%s:%u'.", host.c_str(), port);
00059     setSocketState(SocketConnected);
00060     connectedEvent(this);
00061   }
00062 #ifndef WIN32
00063   else if(errno != EINPROGRESS)
00064 #else
00065   else if(WSAGetLastError() != WSAEINPROGRESS)
00066 #endif // ! WIN32
00067   {
00068     NNLOG("newnet.net.warn", "Cannot connect to host '%s:%u', error: %i.", host.c_str(), port, errno);
00069     setSocketError(ErrorCannotConnect);
00070     cannotConnectEvent(this);
00071   }
00072 }

Generated on Sun Jan 7 14:00:01 2007 for NewNet by  doxygen 1.5.1