bool Socket::connect(std::string url, int port) { int err; if(isalpha(url[0])) url = SocketSystem().getIpFromName(url); SOCKADDR_IN tcpAddr; tcpAddr.sin_family = AF_INET; tcpAddr.sin_addr.s_addr = inet_addr(url.c_str()); tcpAddr.sin_port = htons(port); err = ::connect(s_, (sockaddr*)&tcpAddr, sizeof(tcpAddr)); if(err == SOCKET_ERROR) return false; return true; }
bool Socket::connect(std::string url, int port, bool throwError, size_t MaxTries) { try { if(isalpha(url[0])) url = SocketSystem().getIpFromName(url); } catch(...) { if(throwError) throw std::exception(ss_.GetLastMsg(true).c_str()); return false; } SOCKADDR_IN tcpAddr; tcpAddr.sin_family = AF_INET; tcpAddr.sin_addr.s_addr = inet_addr(url.c_str()); tcpAddr.sin_port = htons(port); if(s_ == INVALID_SOCKET) { s_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } size_t tryCount = 0; std::string countStr; while(true) { ++tryCount; TRACE("attempt to connect #" + IntToString(tryCount)); int err = ::connect(s_, (sockaddr*)&tcpAddr, sizeof(tcpAddr)); //std::string rip = System().getRemoteIP(this); int rport = System().getRemotePort(this); // error return from connect does not appear to be reliable if(err != SOCKET_ERROR && rport != -1) break; if(tryCount >= MaxTries) { if(throwError) throw std::exception(ss_.GetLastMsg(true).c_str()); return false; } ::Sleep(100); } TRACE("I believe we are connected to " + url); return true; }