void HostCatcher::noteHostBad( HostAddress * inHost ) { mLock->lock(); // make sure this host already exists in our list char exists = false; HostAddress *foundHost = NULL; int numHosts = mHostVector->size(); for( int i=0; i<numHosts; i++ ) { HostAddress *otherHost = *( mHostVector->getElement( i ) ); if( otherHost->equals( inHost ) ) { exists = true; // delete the host that we've found mHostVector->deleteElement( i ); foundHost = otherHost; // jump out of loop i = numHosts; } } if( exists ) { delete foundHost; //mHostVector->push_back( foundHost ); } mLock->unlock(); }
HostAddress * HostCatcher::getHost( ) { mLock->lock(); int numHosts = mHostVector->size(); if( numHosts == 0 ) { mLock->unlock(); return NULL; } // remove random host from queue int index = mRandSource->getRandomBoundedInt( 0, numHosts - 1 ); HostAddress *host = *( mHostVector->getElement( index ) ); mHostVector->deleteElement( index ); // add host to end of queue mHostVector->push_back( host ); HostAddress *hostCopy = host->copy(); mLock->unlock(); return hostCopy; }
static Boolean isListenAddressValid(const String value_) { if(value_.size() == 0 ) { return false; } Boolean isIpListTrue = true; Array<String> interfaces = DefaultPropertyOwner::parseAndGetListenAddress( value_); HostAddress theAddress; for(Uint32 i = 0, m = interfaces.size(); i < m; ++i) { if(!theAddress.setHostAddress(interfaces[i])) { isIpListTrue = false; throw InvalidListenAddressPropertyValue( "listenAddress", interfaces[i]); break; } } return isIpListTrue; }
HostAddress *HostAddress::getLocalAddress() { int bufferLength = 200; char *buffer = new char[ bufferLength ]; gethostname( buffer, bufferLength ); char *name = stringDuplicate( buffer ); delete [] buffer; // this class will destroy name for us HostAddress *nameAddress = new HostAddress( name, 0 ); HostAddress *fullAddress = nameAddress->getNumericalAddress(); if( fullAddress != NULL ) { delete nameAddress; return fullAddress; } else { return nameAddress; } }
HostAddress * HostCatcher::getHostOrdered( ) { mLock->lock(); int numHosts = mHostVector->size(); if( numHosts == 0 ) { mLock->unlock(); return NULL; } // remove first host from queue HostAddress *host = *( mHostVector->getElement( 0 ) ); mHostVector->deleteElement( 0 ); // add host to end of queue mHostVector->push_back( host ); HostAddress *hostCopy = host->copy(); mLock->unlock(); return hostCopy; }
void TUIServerApp::handleSystemCmdMsg(HostEvent * msg) { HostAddress address = msg->getAddress(); SystemCmdMsg * msg2 = static_cast<SystemCmdMsg *>(msg->getPayload()); const SystemCmd & systemCmd = msg2->getPayload(); address.setPortNr(systemCmd.getPortNr()); if (systemCmd.getCmd() == SystemCmd::requestConnection) { TFDEBUG("SystemCmdMsg::RequestConnection: " << address); this->outHostMsgDispatcher.addDstAddress(address); if (this->usingMulticast) { MulticastGroupInvitationMsg * event = new MulticastGroupInvitationMsg(); event->setPayload(this->multicastGroup); this->outEventQueue.push(event); } { { GUIDEventTypeIDVectorMsg * event = new GUIDEventTypeIDVectorMsg(); event->setPayload(this->guidEventTypeIDVector); this->outEventQueue.push(event); } { AttachedObjectsMsg * event = new AttachedObjectsMsg(); event->setPayload(this->attachedObjects); this->outEventQueue.push(event); } } } else if (systemCmd.getCmd() == SystemCmd::removeConnection) { TFDEBUG("SystemCmdMsg::RemoveConnection: " << address); this->outHostMsgDispatcher.removeDstAddress(address); } }
HostAddress HostAddress::fromString(std::string str) { HostAddress h; h.address_str = str; h.parse_string(); h.initialised = true; return h; }
Byte BinaryImage::readNative1(Address addr) const { const BinarySection *section = getSectionByAddr(addr); if (section == nullptr || section->getHostAddr() == HostAddress::INVALID) { LOG_WARN("Invalid read at address %1: Address is not mapped to a section", addr); return 0xFF; } HostAddress host = section->getHostAddr() - section->getSourceAddr() + addr; return *reinterpret_cast<Byte *>(host.value()); }
void HostCatcher::addHost( HostAddress * inHost ) { // convert to numerical form once and for all here // (to avoid converting over and over in equals checks below) HostAddress *numericalAddress = inHost->getNumericalAddress(); if( numericalAddress != NULL ) { mLock->lock(); // make sure this host doesn't already exist in our list char exists = false; int numHosts = mHostVector->size(); for( int i=0; i<numHosts; i++ ) { HostAddress *otherHost = *( mHostVector->getElement( i ) ); if( otherHost->equals( numericalAddress ) ) { exists = true; // jump out of loop i = numHosts; } } if( !exists ) { mHostVector->push_back( numericalAddress->copy() ); } while( mHostVector->size() > mMaxListSize ) { // remove first host from queue HostAddress *host = *( mHostVector->getElement( 0 ) ); mHostVector->deleteElement( 0 ); delete host; } mLock->unlock(); delete numericalAddress; } }
Connection(ProactorFile *socket, const HostAddress &addr): mSrcSocket(socket), mDestSocket(nullptr), mRespForwardedPos(0), mCountOfEOF(0) { mID = format("Connection(%d,%s)", socket->getFd(), addr.toString().c_str()); LOG("Connection(%s) established ...", getID()); mSrcSocket->readLine('\n', [this](bool eof, const char *buf, int n){ onReadRequestline(eof, buf, n); }); }
bool BinaryImage::writeNative4(Address addr, uint32_t value) { BinarySection *si = getSectionByAddr(addr); if (si == nullptr || si->getHostAddr() == HostAddress::INVALID) { LOG_WARN("Ignoring write at address %1: Address is outside any writable section"); return false; } else if (addr + 4 > si->getSourceAddr() + si->getSize()) { LOG_WARN("Invalid write at address %1: Write extends past section boundary", addr); return false; } si->addDefinedArea(addr, addr + 4); HostAddress host = si->getHostAddr() - si->getSourceAddr() + addr; Util::writeDWord(reinterpret_cast<void *>(host.value()), value, si->getEndian()); return true; }
QWord BinaryImage::readNative8(Address addr) const { const BinarySection *si = getSectionByAddr(addr); if (si == nullptr || si->getHostAddr() == HostAddress::INVALID) { LOG_WARN("Invalid read at address %1: Address is not mapped to a section", addr.toString()); return 0x0000000000000000; } else if (addr + 8 > si->getSourceAddr() + si->getSize()) { LOG_WARN("Invalid read at address %1: Read extends past section boundary", addr); return 0x0000000000000000; } else if (si->isAddressBss(addr)) { return 0x0000000000000000; } HostAddress host = si->getHostAddr() - si->getSourceAddr() + addr; return Util::readQWord(reinterpret_cast<const Byte *>(host.value()), si->getEndian()); }
bool Network::UdpSocket::bind(const HostAddress& address, uint16 port) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = address.toIPv4Address(); addr.sin_port = htons(port); if (::bind(_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) return (false); return (true); }
bool TcpSocket::ConnectToHost(const string& hostName, const string& port, IBamIODevice::OpenMode mode) { // create new address object with requested host name HostAddress hostAddress; hostAddress.SetAddress(hostName); HostInfo info; // if host name was IP address ("x.x.x.x" or IPv6 format) // otherwise host name was 'plain-text' ("www.foo.bar") // we need to look up IP address(es) if ( hostAddress.HasIPAddress() ) info.SetAddresses( vector<HostAddress>(1, hostAddress) ); else info = HostInfo::Lookup(hostName, port); // attempt connection on requested port return ConnectImpl(info, port, mode); }
HostAddress *HostAddress::getLocalAddress() { // first make sure sockets are initialized if( !Socket::isFrameworkInitialized() ) { // try to init the framework int error = Socket::initSocketFramework(); if( error == -1 ) { printf( "initializing network socket framework failed\n" ); return NULL; } } int bufferLength = 200; char *buffer = new char[ bufferLength ]; gethostname( buffer, bufferLength ); char *name = stringDuplicate( buffer ); delete [] buffer; // this class will destroy name for us HostAddress *nameAddress = new HostAddress( name, 0 ); HostAddress *fullAddress = nameAddress->getNumericalAddress(); delete nameAddress; return fullAddress; }
/*---------------------------------------------------------------------*/ void receiver(Socket* socket) { HostAddress peer; TextMessage msg(1024); try { do { socket->Receive(peer, msg); printf("[%s] msg=%s", peer.GetHost(), msg.GetBuffer()); } while ( strcmp(msg.GetBuffer(), "bye\n") != 0 ); } catch (Exception& err) { printf("[CHILD]"); err.PrintException(); } catch (...) { fprintf(stderr, "Unknown error\n"); } exit(0); }
bool RedisProxy::run(const HostAddress& addr) { if (isRunning()) { return false; } if (m_vipEnabled) { TcpSocket sock = TcpSocket::createTcpSocket(); Logger::log(Logger::Message, "connect to vip address(%s:%d)...", m_vipAddress, addr.port()); if (!sock.connect(HostAddress(m_vipAddress, addr.port()))) { Logger::log(Logger::Message, "set VIP [%s,%s]...", m_vipName, m_vipAddress); int ret = NonPortable::setVipAddress(m_vipName, m_vipAddress, 0); Logger::log(Logger::Message, "set_vip_address return %d", ret); } else { m_vipSocket = sock; m_vipEvent.set(eventLoop(), sock.socket(), EV_READ, vipHandler, this); m_vipEvent.active(); } } m_monitor->proxyStarted(this); Logger::log(Logger::Message, "Start the %s on port %d", APP_NAME, addr.port()); RedisCommand cmds[] = { {"HASHMAPPING", 11, -1, onHashMapping, NULL}, {"ADDKEYMAPPING", 13, -1, onAddKeyMapping, NULL}, {"DELKEYMAPPING", 13, -1, onDelKeyMapping, NULL}, {"SHOWMAPPING", 11, -1, onShowMapping, NULL}, {"POOLINFO", 8, -1, onPoolInfo, NULL}, {"SHUTDOWN", 8, -1, onShutDown, this} }; RedisCommandTable::instance()->registerCommand(cmds, sizeof(cmds)/sizeof(RedisCommand)); return TcpServer::run(addr); }
int main(int argc, char **argv) { //// The string must have the format n.n.n.n:p, where n /// has the range 0 - 255 and p has the range from 0 to 65535 if (argc != 3) { cout << "Error: Usage <receiver ip>:<receiver port> <0|1> <0|1>." << endl; cout << "The string must have the format n.n.n.n:p, where n has the range 0 - 255 and p has the range from 0 to 65535" << endl; cout << "The programm is startet with OpenGL, if the second parameter is 1." << endl; return 1; } //serveradd, where the kinectDevice-object is located hostadd.fromString(argv[1]); std::cout << "TUIDevice - MotionCaptureStub IPAddress: " << argv[1] << std::endl; enableOpenGL = atoi(argv[2]); /// initialize openNi, kinect initOpenNi(); /// initialize udp sender, which sends the serialized joints sender.setMyPort(0); sender.create(); if(enableOpenGL) { std::cout << "starting opengl " << std::endl; glInit(&argc, argv); glutMainLoop(); } else { /// actual reading and sending of the data executeInputLoop(); } /// close all openNi stuff CleanupExit(); return 0; }
void testToString_Invalid() { HostAddress testling; CPPUNIT_ASSERT_EQUAL(std::string("0.0.0.0"), testling.toString()); }
void ExportClient::_connect() { PEG_METHOD_ENTER (TRC_EXPORT_CLIENT,"ExportClient::_connect()"); if(!isWSMANExportIndication) { // Create response decoder: _cimResponseDecoder = new CIMExportResponseDecoder( this, _cimRequestEncoder, &_authenticator); // Attempt to establish a connection: try { _httpConnection = _httpConnector->connect(_connectHost, _connectPortNumber, _connectSSLContext.get(), _timeoutMilliseconds, _cimResponseDecoder); } catch (...) { // Some possible exceptions are CannotCreateSocketException, // CannotConnectException, and InvalidLocatorException delete _cimResponseDecoder; PEG_METHOD_EXIT(); throw; } } else { #ifdef PEGASUS_ENABLE_PROTOCOL_WSMAN // Create response decoder: _wsmanResponseDecoder = new WSMANExportResponseDecoder( this, _wsmanRequestEncoder, &_authenticator); // Attempt to establish a connection: try { _httpConnection = _httpConnector->connect(_connectHost, _connectPortNumber, _connectSSLContext.get(), _timeoutMilliseconds, _wsmanResponseDecoder); } catch(...) { // Some possible exceptions are CannotCreateSocketException, // CannotConnectException, and InvalidLocatorException delete _wsmanResponseDecoder; PEG_METHOD_EXIT(); throw; } #endif } String connectHost = _connectHost; #ifdef PEGASUS_ENABLE_IPV6 HostAddress hst; hst.setHostAddress(connectHost); if (hst.getAddressType() == HostAddress::AT_IPV6) { connectHost = "[" + connectHost + "]"; } #endif char portStr[32]; if (connectHost.size()) { sprintf(portStr, ":%u", _connectPortNumber); connectHost.append(portStr); } #ifdef PEGASUS_ENABLE_PROTOCOL_WSMAN //Create requestEncoder to encode the exportIndication request. if(isWSMANExportIndication) { _wsmanRequestEncoder= new WSMANExportRequestEncoder( _httpConnection, _connectHost, portStr, &_authenticator); _wsmanResponseDecoder->setEncoderQueue(_wsmanRequestEncoder); } else #endif { _cimRequestEncoder = new CIMExportRequestEncoder( _httpConnection, connectHost, &_authenticator); _cimResponseDecoder->setEncoderQueue(_cimRequestEncoder); _doReconnect = false; } _connected = true; _httpConnection->setSocketWriteTimeout(_timeoutMilliseconds/1000+1); PEG_METHOD_EXIT(); }
PEGASUS_NAMESPACE_BEGIN static bool _parseLocator( const String &locator, HostAddress& addr, Uint32& port) { const Uint16* first = (const Uint16*)locator.getChar16Data(); const Uint16* last = first + locator.size(); port = HostLocator::PORT_UNSPECIFIED; // Reject zero length locators. if (first == last) { return false; } // Parse the host address. const Uint16* p = first; if (*p == '[') { // Parse "[...]" expresion. const Uint16* start = ++p; while (*p && *p != ']') p++; if (*p != ']') { return false; } addr.setHostAddress(String((const Char16*)start, p - start)); p++; // Only IPV6 addresses may be enclosed in braces. if (addr.getAddressType() != HostAddress::AT_IPV6) { return false; } } else { // Find end-of-string host address (null terminator or colon). const Uint16* start = p; while (*p && *p != ':') p++; addr.setHostAddress(String((const Char16*)start, p - start)); if (!addr.isValid()) { return false; } // IPV6 addresses must be enclosed in braces. if (addr.getAddressType() == HostAddress::AT_IPV6) { return false; } } // Parse the port number: if (*p == ':') { const Uint16* start = ++p; // If empty port number, ignore and proceed as unspecified port. if (start == last) { return true; } port = HostLocator::PORT_INVALID; // Convert string port number to integer (start at end of string). Uint32 r = 1; Uint32 x = 0; for (const Uint16* q = last; q != start; q--) { Uint16 c = q[-1]; if (c > 127 || !isdigit(c)) return false; x += r * (c - '0'); r *= 10; } if (x > HostLocator::MAX_PORT_NUMBER) { return false; } port = x; p++; return true; } else if (*p != '\0') { return false; } // Unreachable! return true; }
HostInfo HostInfo::Lookup(const string& hostname, const string& port) { HostInfo result; result.SetHostName(hostname); set<HostAddress> uniqueAddresses; #ifdef _WIN32 WindowsSockInit init; #endif HostAddress address; address.SetAddress(hostname); // if hostname is an IP string ('0.0.0.0' or IPv6 format) // do reverse lookup for host domain name // // TODO: might just remove this... not sure if proper 'hostname' from IP string is needed // // so far, haven't been able to successfully fetch a domain name with reverse DNS // getnameinfo() on test sites just returns original IP string. BUT this is likely a rare // case that client code tries to use an IP string and the connection should work fine // anyway. GetHostName() just won't quite show what I was hoping for. :( if ( address.HasIPAddress() ) { const uint16_t portNum = static_cast<uint16_t>( atoi(port.c_str()) ); sockaddr_in sa4; sockaddr_in6 sa6; sockaddr* sa = 0; BT_SOCKLEN_T saSize = 0; // IPv4 if ( address.GetProtocol() == HostAddress::IPv4Protocol ) { sa = (sockaddr*)&sa4; saSize = sizeof(sa4); memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; sa4.sin_addr.s_addr = htonl(address.GetIPv4Address()); sa4.sin_port = htons(portNum); } // IPv6 else if ( address.GetProtocol() == HostAddress::IPv4Protocol ){ sa = (sockaddr*)&sa6; saSize = sizeof(sa6); memset(&sa6, 0, sizeof(sa6)); sa6.sin6_family = AF_INET6; memcpy(sa6.sin6_addr.s6_addr, address.GetIPv6Address().data, sizeof(sa6.sin6_addr.s6_addr)); sa6.sin6_port = htons(portNum); } // unknown (should be unreachable) else BT_ASSERT_X(false, "HostInfo::Lookup: unknown network protocol"); // lookup name for IP char hbuf[NI_MAXHOST]; char serv[NI_MAXSERV]; if ( sa && (getnameinfo(sa, saSize, hbuf, sizeof(hbuf), serv, sizeof(serv), 0) == 0) ) result.SetHostName(string(hbuf)); // if no domain name found, just use the original address's IP string if ( result.HostName().empty() ) result.SetHostName(address.GetIPString()); // store address in HostInfo uniqueAddresses.insert(address); } // otherwise, hostname is a domain name ('www.foo.bar') // do 'normal' lookup else { // setup address lookup 'hints' addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; // allow either IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // for TCP hints.ai_protocol = IPPROTO_TCP; // fetch addresses for requested hostname/port addrinfo* res; int status = getaddrinfo(hostname.c_str(), port.c_str(), &hints, &res ); // if everything OK if ( status == 0 ) { // iterate over all IP addresses found addrinfo* p = res; for ( ; p != NULL; p = p->ai_next ) { // IPv4 if ( p->ai_family == AF_INET ) { sockaddr_in* ipv4 = (sockaddr_in*)p->ai_addr; HostAddress a( ntohl(ipv4->sin_addr.s_addr) ); uniqueAddresses.insert(a); } // IPv6 else if ( p->ai_family == AF_INET6 ) { sockaddr_in6* ipv6 = (sockaddr_in6*)p->ai_addr; HostAddress a(ipv6->sin6_addr.s6_addr); uniqueAddresses.insert(a); } } // if we iterated, but no addresses were stored if ( uniqueAddresses.empty() && (p == NULL) ) { result.SetError(HostInfo::UnknownError); result.SetErrorString("HostInfo: unknown address types found"); } } // handle error cases else if ( #ifndef _WIN32 status == EAI_NONAME || status == EAI_FAIL # ifdef EAI_NODATA || status == EAI_NODATA // officially deprecated, but just in case we happen to hit it # endif // EAI_NODATA #else // _WIN32 WSAGetLastError() == WSAHOST_NOT_FOUND || WSAGetLastError() == WSANO_DATA || WSAGetLastError() == WSANO_RECOVERY #endif // _WIN32 ) { result.SetError(HostInfo::HostNotFound); result.SetErrorString("HostInfo: host not found"); } else { result.SetError(HostInfo::UnknownError); result.SetErrorString("HostInfo: unknown error encountered"); } // cleanup freeaddrinfo(res); } // store fetched addresses (converting set -> vector) in result & return result.SetAddresses( vector<HostAddress>(uniqueAddresses.begin(), uniqueAddresses.end()) ); return result; }
SimpleVector<HostAddress *> *HostCatcher::getHostList( int inMaxHostCount, HostAddress *inSkipHost ) { HostAddress *hostToSkip; if( inSkipHost != NULL ) { hostToSkip = inSkipHost->copy(); } else { // don't skip any host // create a dummy host that won't match any other valid hosts // make sure dummy is in numerical form to avoid DNS lookups hostToSkip = new HostAddress( stringDuplicate( "1.1.1.1" ), 1 ); } SimpleVector<HostAddress *> *collectedHosts = new SimpleVector<HostAddress *>(); char repeat = false; int numCollected = 0; // This function assumes that getHostOrdered() draws // hosts in order with no repetition except when we have // exhausted the host supply. // Note that this will not be true when other threads // have getHostOrdered() (or getHost) calls interleaved with ours, but this // should be a rare case. It will simply result // in a smaller host list being returned. HostAddress *firstHost = getHostOrdered(); if( firstHost == NULL ) { // the catcher is empty delete hostToSkip; // an empty host list return collectedHosts; } if( ! hostToSkip->equals( firstHost ) ) { collectedHosts->push_back( firstHost ); numCollected++; } while( numCollected < inMaxHostCount && !repeat ) { HostAddress *nextHost = getHostOrdered(); if( nextHost->equals( firstHost ) ) { delete nextHost; repeat = true; } else { if( ! hostToSkip->equals( nextHost ) ) { collectedHosts->push_back( nextHost ); numCollected++; } else { delete nextHost; } } } if( hostToSkip->equals( firstHost ) ) { // we didn't include firstHost in our collectedHosts, so // we must delete it. delete firstHost; } delete hostToSkip; return collectedHosts; }
int main() { char *name = new char[99]; sprintf( name, "63.249.65.249" ); //char *name = new char[99]; //sprintf( name, "192.168.1.2" ); //char *name = "192.168.1.1"; //int addressLength = 11; //char *name = "monolith.2y.net"; //int addressLength = 15; int port = 5158; HostAddress *address = new HostAddress( name, port ); printf( "Trying to connect to server: " ); address->print(); printf( "\n" ); Socket *sock; int numConnections = 0; while( true ) { sock = SocketClient::connectToServer( address ); if( sock == NULL ) { printf( "%d Connecting to server failed\n", numConnections ); //return 1; } else { printf( "%d Connection established\n", numConnections ); HostAddress *localAddress = sock->getLocalHostAddress(); if( localAddress != NULL ) { printf( "Our local address (fetched from socket) is " ); localAddress->print(); printf( "\n" ); delete localAddress; } delete sock; } //usleep( 1000 ); numConnections++; } int numBytes = 4000; unsigned char *buffer = new unsigned char[numBytes]; for( int i=0; i<numBytes; i++ ) { buffer[i] = i; } SocketStream *stream = new SocketStream( sock ); //printf( "sleeping\n" ); //sleep( 10 ); int count = 0; while( true ) { printf( "sending %d bytes\n", numBytes ); int numSent = stream->write( buffer, numBytes ); printf( "Sent %d successfully,\tcount = %d\n", numSent, count ); count++; } int checksum = 0; for( int i=0; i<numBytes; i++ ) { checksum += buffer[ i ]; } printf( "Checksum: %d\n", checksum ); printf( "Deleting stream\n" ); delete stream; printf( "Deleting socket\n" ); delete sock; printf( "Deleting address\n" ); delete address; printf( "Returning\n" ); return 0; }
void testConstructor_Invalid() { HostAddress testling; CPPUNIT_ASSERT(!testling.isValid()); }
bool TcpSocketEngine::nativeConnect(const HostAddress& address, const uint16_t port) { // setup connection parameters from address/port sockaddr_in sockAddrIPv4; sockaddr_in6 sockAddrIPv6; sockaddr* sockAddrPtr = 0; BT_SOCKLEN_T sockAddrSize = 0; // IPv6 if ( address.GetProtocol() == HostAddress::IPv6Protocol ) { memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6)); sockAddrIPv6.sin6_family = AF_INET6; sockAddrIPv6.sin6_port = htons(port); IPv6Address ip6 = address.GetIPv6Address(); memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &ip6, sizeof(ip6)); sockAddrSize = sizeof(sockAddrIPv6); sockAddrPtr = (sockaddr*)&sockAddrIPv6; } // IPv4 else if ( address.GetProtocol() == HostAddress::IPv4Protocol ) { memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4)); sockAddrIPv4.sin_family = AF_INET; sockAddrIPv4.sin_port = htons(port); sockAddrIPv4.sin_addr.s_addr = htonl(address.GetIPv4Address()); sockAddrSize = sizeof(sockAddrIPv4); sockAddrPtr = (sockaddr*)&sockAddrIPv4; } // unknown (should be unreachable) else BT_ASSERT_X(false, "TcpSocketEngine::nativeConnect() : unknown network protocol"); // attempt connection int connectResult = connect(m_socketDescriptor, sockAddrPtr, sockAddrSize); // if failed, handle error if ( connectResult == -1 ) { // ensure state is set before checking errno m_socketState = TcpSocket::UnconnectedState; // set error type/message depending on errno switch ( errno ) { // <-- potential thread issues later? but can't get error type from connectResult case EISCONN: m_socketState = TcpSocket::ConnectedState; // socket was already connected break; case ECONNREFUSED: case EINVAL: m_socketError = TcpSocket::ConnectionRefusedError; m_errorString = "connection refused"; break; case ETIMEDOUT: m_socketError = TcpSocket::NetworkError; m_errorString = "connection timed out"; break; case EHOSTUNREACH: m_socketError = TcpSocket::NetworkError; m_errorString = "host unreachable"; break; case ENETUNREACH: m_socketError = TcpSocket::NetworkError; m_errorString = "network unreachable"; break; case EADDRINUSE: m_socketError = TcpSocket::SocketResourceError; m_errorString = "address already in use"; break; case EACCES: case EPERM: m_socketError = TcpSocket::SocketAccessError; m_errorString = "permission denied"; break; default: break; } // double check that we're not in 'connected' state; if so, return failure if ( m_socketState != TcpSocket::ConnectedState ) return false; } // otherwise, we should be good // update state & return success m_socketState = TcpSocket::ConnectedState; return true; }
bool HostAddress::operator==(const HostAddress& other) const { return (other.ip() == ip() && other.port() == port()); }