Ip Address::ip(Ip ip) { #ifdef WINDOWS unsigned long address = inet_addr(ip.c_str()); if (address == INADDR_NONE) { stringstream error; error << "[ip] with [ip=" << ip << "] Invalid ip address provided"; throw SocketException(error.str()); } else { this->sin_addr.S_un.S_addr = address; } #else if (inet_aton(ip.c_str(), &this->sin_addr) == 0) { stringstream error; error << "[ip] with [ip=" << ip << "] Invalid ip address provided"; throw SocketException(error.str()); } #endif return this->ip(); }
void LinkScheduler::on_ip_schedule(evutil_socket_t sock, short event, void *arg) { IpContext *ipContext = (IpContext*)arg; HttpProcessor *httpProcessor = ipContext->linkTable->getLinkScheduler()->_httpProcessor; Ip ip; Site site; UrlContext *urlContext = NULL; bool isIpContextObsolete = ipContext->linkTable->select(ipContext, ip, site, urlContext); LOG_F(DEBUG, "pop ip=%s site=%s url=%s urlContext:%p", ip.c_str(), site.c_str(), urlContext->url.c_str(), urlContext); httpProcessor->pushConnectQueue(urlContext); // select()可能delete掉ipContext if (!isIpContextObsolete) { struct event *ipScheduleEvent = ipContext->ipScheduleEvent; struct timeval t = {ipContext->scheduleInterval, 0 }; evtimer_add(ipScheduleEvent, &t); } }
bool SocketTcp::Connect(const Ip &ip, unsigned short port) { if (!IsValid()) throw Utils::Exception("SocketTcp", "Can't connect, The socket is not valid"); // Build the host address sockaddr_in s; memset(s.sin_zero, 0, sizeof(s.sin_zero)); s.sin_addr.s_addr = inet_addr(ip.ToString().c_str()); s.sin_family = AF_INET; s.sin_port = htons(port); if (connect(_descriptor, reinterpret_cast<sockaddr*>(&s), sizeof(s)) == -1) return false; return true; }
bool SocketTcp::Accept(SocketTcp &newClient, Ip &newclientIp) { if (!IsValid()) throw Utils::Exception("SocketTcp", "Can't accept, The socket is not valid"); sockaddr_in clientAddr; #ifdef SYSTEM_WINDOWS int len = sizeof(clientAddr); #else socklen_t len = sizeof(clientAddr); #endif // Accept a new connection newClient._descriptor = accept(_descriptor, reinterpret_cast<sockaddr*>(&clientAddr), &len); if (!newClient.IsValid()) return false; newclientIp.Init(inet_ntoa(clientAddr.sin_addr)); return true; }
void ClientSocket::connect(const Ip &ip, int port) { sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip.getString().c_str()); addr.sin_port = htons(port); int res = ::connect(sock, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr)); if (res == SOCKET_ERROR) { int errCode = get_error(); if (errCode != WOULD_BLOCK) { handleError(__FUNCTION__); } else { // TODO // wait a bit, check writable, try again cout << "::connect() error, WOULD_BLOCK.\n"; } } else { setNoDelay(); } }