00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
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
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 }