/** Get the internet name of this host. Actually this will always return a null string with TCPIP 030 and onwards because the "name" of a mobile host isn't really very meaningful - in practice the IP address is chosen dynamically once you start doing real networking, at which time the ISP can resolve the IP address into a name of some sort if you really want. @return @param name @param size */ EXPORT_C int gethostname (char *name, size_t size) { int* perrno=__errno(); RSocketServ ss; TInt err=ss.Connect(1); if (err==KErrNone) { RHostResolver r; err=r.Open(ss, AF_INET, KProtocolInetUdp); if (err==KErrNone) { TBuf<128> hostname; err=r.GetHostName(hostname); if (err==KErrNone) { if (size>(size_t)hostname.Length()) { TPtr8 retval((TText8*)name,size); retval.Copy(hostname); retval.PtrZ(); } else err=ENAMETOOLONG; } r.Close(); } ss.Close(); } return MapError(err,*perrno); }
enum TVerdict CTestIdna08::doTestStepL() { INFO_PRINTF1(_L(" Testing the Loading of the new Library ")); INFO_PRINTF1(_L("****************************************")); SetTestStepResult(EFail); // By default start the test case with failure. RLibrary testLibrary; TInt err = testLibrary.Load(_L("punycodeconverter.dll")); if(err == KErrNone) { INFO_PRINTF1(_L(" Loading the punycodeconverter library is successful")); SetTestStepResult(EPass); } else { INFO_PRINTF1(_L(" Loading the punycodeconverter library is NOT successful")); User::LeaveIfError(KErrNone); // just to suppress the LeaveScan warning } INFO_PRINTF1(_L("Negative Testing of SetOpt ")); INFO_PRINTF1(_L("****************************************")); RSocketServ pSocketServ; User::LeaveIfError(pSocketServ.Connect()); RConnection myConnection; myConnection.Open(pSocketServ, KAfInet); TRequestStatus myStatus=KErrNone; myConnection.Start(myStatus); User::WaitForRequest(myStatus); RHostResolver hr; hr.Open(pSocketServ,KAfInet,KProtocolInetUdp); TBool enableIdn = ETrue;//enabling the option of IDN support TPckgC<TBool> pckgEnable(enableIdn); TInt setOptErr = hr.SetOpt(KSoInetConfigInterface , KSolInetDns , pckgEnable); if(setOptErr != KErrNone) { INFO_PRINTF1(_L(" Negative Testing of the Setopt successful ")); SetTestStepResult(EPass); } setOptErr = hr.SetOpt(KSoDnsEnableIdn , KSolInetDns , pckgEnable); User::LeaveIfError(setOptErr); enableIdn = EFalse; TPckgC<TBool> pckgDisable(enableIdn); setOptErr = hr.SetOpt(KSoDnsEnableIdn , KSolInetDns , pckgDisable); User::LeaveIfError(setOptErr); hr.Close(); myConnection.Close(); pSocketServ.Close(); return TestStepResult(); }
// from PDIS miso library // Gets the local device name. // Arguments: // - aName - object to hold the retrieved name. // // Returns an error code. static TInt GetLocalName(TDes& aName) { TInt err = KErrNone; RSocketServ socketServ; err = socketServ.Connect(); if (!err) { TProtocolName protocolName; // address and name queries are apparently supplied // by the BT stack's link manager _LIT(KBtLinkManager, "BTLinkManager"); protocolName.Copy(KBtLinkManager); TProtocolDesc protocolDesc; err = socketServ.FindProtocol(protocolName, protocolDesc); if (!err) { RHostResolver hostResolver; err = hostResolver.Open(socketServ, protocolDesc.iAddrFamily, protocolDesc.iProtocol); if (!err) { err = hostResolver.GetHostName(aName); hostResolver.Close(); } } socketServ.Close(); } return err; }
// Looks up the name of the device with the given address. // Arguments: // - wantedAddr - address of the device to look up. Note that the address // is expected without colons!! e.g. "000D9319C868" // - aDeviceName - the object to hold the name once it is found // - ignoreCache - if True, performs a remote name request even if the device // name is known in the cache from a previous request. // // Returns an error code. static TInt LookupName(TBTDevAddr& wantedAddr, THostName* aDeviceName, bool ignoreCache) { TInt err = KErrNone; RSocketServ socketServer; RHostResolver hostResolver; TRequestStatus status; TNameEntry nameEntry; // make a TInquirySockAddr with the address of the device we want to look up TBTSockAddr sockAddr; sockAddr.SetBTAddr(wantedAddr); TInquirySockAddr addr = addr.Cast(sockAddr); // connect err = socketServer.Connect(); if (err) return err; // load protocol for discovery TProtocolDesc protocolDesc; err = socketServer.FindProtocol(_L("BTLinkManager"), protocolDesc); if (!err) { // initialize host resolver err = hostResolver.Open(socketServer, protocolDesc.iAddrFamily, protocolDesc.iProtocol); if (!err) { // Request name lookup. // We don't need to call SetIAC() if we're just doing name lookup. // Don't put KHostResInquiry flag in SetAction(), because that // will start a device inquiry, when we just want to find the one // name. if (ignoreCache) { addr.SetAction(KHostResName|KHostResIgnoreCache); } else { addr.SetAction(KHostResName); } hostResolver.GetByAddress(addr, nameEntry, status); User::WaitForRequest(status); if (status == KErrNone) { *aDeviceName = nameEntry().iName; err = KErrNone; } else { err = KErrGeneral; } hostResolver.Close(); } } socketServer.Close(); return err; }
void CMSocketS::Listen() { if (m_status != IDLE) { m_pNotify->OnAccept(MERN_INITIALIZE, NULL); return; } CMNetConnMgr& mgr = CMNetConnMgr::Instance(); //网络未接入直接返回失败 if (mgr.CurrentType() == CMNetConnMgr::NONE) { // m_pNotify->OnAccept(MERN_INITIALIZE, NULL); } //构造本地侦听ip,端口 RHostResolver hostResolver; TNameEntry entry; TInetAddr aAddress; User::LeaveIfError( hostResolver.Open( mgr.SocketServer(), KAfInet, KProtocolInetTcp, mgr.Connection() )); CleanupClosePushL( hostResolver ); User::LeaveIfError(hostResolver.GetByName(TPtrC(), entry)); if (!TInetAddr::Cast(entry().iAddr).IsWildAddr()) { aAddress = TInetAddr::Cast(entry().iAddr); } CleanupStack::PopAndDestroy(); // hostResolver aAddress.SetPort(m_nPort); //开始侦听 User::LeaveIfError( m_sk.Open( mgr.SocketServer(), KAfInet, KSockStream, KProtocolInetTcp ) ); User::LeaveIfError( m_sk.Bind( aAddress ) ); User::LeaveIfError( m_sk.Listen( 1 ) ); CMSocketC* pSocketC = new CMSocketC(NULL); // pSocketC->m_status = CMSocketC::CONNECTED; // if (pSocketC == NULL || pSocketC->GetStatus() != CMSocketC::NOTCONNECTED) // { // m_pNotify->OnAccept(MERN_WRONG_PARAM, NULL); // return; // } User::LeaveIfError( pSocketC->m_sk.Open( mgr.SocketServer() ) ); m_sk.Accept( pSocketC->m_sk, iStatus ); m_status = LISTENING; m_pSocketC = pSocketC; SetActive(); }
enum TVerdict CTestIdna04::doTestStepL() { INFO_PRINTF1(_L(" Testing GetByAddress(for an IDN) with IDN Enabled ")); INFO_PRINTF1(_L("*********************************************************")); SetTestStepResult(EFail); // By default start the test case with failure. RSocketServ pSocketServ; User::LeaveIfError(pSocketServ.Connect()); RConnection myConnection; myConnection.Open(pSocketServ, KAfInet); TRequestStatus myStatus=KErrNone; myConnection.Start(myStatus); User::WaitForRequest(myStatus); RHostResolver hr; hr.Open(pSocketServ,KAfInet,KProtocolInetUdp); TBool enableIdn = ETrue;//enabling the option of IDN support TPckgC<TBool> pckgEnable(enableIdn); TInt setOptErr = hr.SetOpt(KSoDnsEnableIdn , KSolInetDns , pckgEnable); User::LeaveIfError(setOptErr); TInetAddr inetAddr; //inetAddr.Input(_L("83.241.177.38")); // this is the IPAddress of the domain räksmörgås.josefsson.org // as of 06 Feb 2009. If this IP changes, this test case might fail // but no harm on this. //TNameEntry resultEntry; inetAddr.Input(_L("64.233.169.103")); TNameRecord asdf; TPckgBuf<TNameRecord> resultEntry(asdf); hr.GetByAddress(inetAddr,resultEntry,myStatus); User::WaitForRequest(myStatus); TInt err = myStatus.Int(); if(err == KErrNone) { INFO_PRINTF2(_L(" GetByAddress with IDN disabled returned %d"),err); SetTestStepResult(EPass); } hr.Close(); myConnection.Close(); pSocketServ.Close(); return TestStepResult(); }
SOAP_SOCKET CAafSocketUtils::SocketOpen(struct soap *soap, const char *endpoint, const char *host, int port) { __LOGSTR_TOFILE("CAafSocketUtils::SocketOpen() begins"); // Set endpoint if (endpoint) strncpy(soap->endpoint, endpoint, sizeof(soap->endpoint)-1); // Get thread entry point data MGSoapData* entryPointData = reinterpret_cast<MGSoapData*>(soap->user); // Open socket entryPointData->GetSocketInstance()->Open(*entryPointData->GetConnectionManager()->GetSocketServ(), KAfInet, KSockStream, KProtocolInetTcp, *entryPointData->GetConnectionManager()->GetConnection()); RHostResolver hostResolver; // Open resolver socket User::LeaveIfError(hostResolver.Open(*entryPointData->GetConnectionManager()->GetSocketServ(), KAfInet, KProtocolInetTcp)) ; TNameEntry hostAddress; TRequestStatus status; HBufC* serverName = CAafUtils::StringToDescriptorLC(host); // Attempt to resolve name hostResolver.GetByName(*serverName, hostAddress, status); CleanupStack::PopAndDestroy(serverName); User::WaitForRequest(status); // Connect to the specified host TInetAddr addrOnPort; addrOnPort = hostAddress().iAddr; addrOnPort.SetPort((TUint)port); entryPointData->GetSocketInstance()->Connect(addrOnPort, status); User::WaitForRequest(status); __LOGSTR_TOFILE("CAafSocketUtils::SocketOpen() ends"); if (status.Int() == KErrNone) return SOAP_OK; return SOAP_ERR; }
void UT_MNATFWMediaWrapper::UT_MNATFWMediaWrapper_SetReceivingStateLL() { // UDP: iSocketMediaConnWrapper->OutgoingAddr( iAddress ); NATFW_EUNIT_ASSERT_NO_LEAVE( iSocketMediaConnWrapper->SetIncomingAddrL( iSenderAddr ) ); NATFW_EUNIT_ASSERT_NO_LEAVE( iSocketMediaConnWrapper->SetReceivingStateL( EStreamingStateActive ) ); NATFW_EUNIT_ASSERT_SPECIFIC_LEAVE( iSocketMediaConnWrapper->SetReceivingStateL( EStreamingStateActive ), KErrInUse ); NATFW_EUNIT_ASSERT_NO_LEAVE( iSocketMediaConnWrapper->SetSendingStateL( EStreamingStateActive ) ); NATFW_EUNIT_ASSERT_NO_LEAVE( iMediaWrapper->SetReceivingStateForMuxWrapper( EStreamingStateActive ) ); iMessage = EEmpty; RHostResolver hr; iData.Append( KData ); // Open Host Resolver associated with the connection User::LeaveIfError( hr.Open( iSocketSrv, KAfInet, KProtocolInetUdp ) ); TNameEntry log; THostName name; User::LeaveIfError( hr.GetByName(name,log) ); User::LeaveIfError( iSocket.Open( iSocketSrv, KAfInet, KSockDatagram, KProtocolInetUdp )); iSocket.SetLocalPort( iSenderAddr.Port() ); log().iAddr.SetPort( iAddress.Port() ); iSocket.SendTo( iData, log().iAddr, 0, iStatus ); User::WaitForRequest( iStatus ); User::LeaveIfError( iStatus.Int() ); iWaitScheduler->Start(); if ( iMessage != EReceivedFrom ) { EUNIT_ASSERT( EFalse ); } EUNIT_PRINT( iReceiveBuffer ); iSocket.Close(); // Deactivate receiving NATFW_EUNIT_ASSERT_NO_LEAVE( iMediaConnWrapper->SetReceivingStateL( EStreamingStatePassive ) ); NATFW_EUNIT_ASSERT_NO_LEAVE( iSocketMediaConnWrapper->SetReceivingStateL( EStreamingStateActive ) ); }
enum TVerdict CTestIdna02::doTestStepL() { INFO_PRINTF1(_L(" Testing GetByName(IDN) with IDN Enabled ")); INFO_PRINTF1(_L("****************************************************")); SetTestStepResult(EFail); // By default start the test case with failure. RSocketServ pSocketServ; User::LeaveIfError(pSocketServ.Connect()); RConnection myConnection; myConnection.Open(pSocketServ, KAfInet); TRequestStatus myStatus=KErrNone; myConnection.Start(myStatus); User::WaitForRequest(myStatus); _LIT(KTestName1,"räksmörgås.josefsson.org"); TName myHostName = KTestName1(); TNameEntry myResolvedName; RHostResolver hr; hr.Open(pSocketServ,KAfInet,KProtocolInetUdp); TBool enableIdn = ETrue;//enabling the option of IDN support TPckgC<TBool> pckgEnable(enableIdn); TInt setOptErr = hr.SetOpt(KSoDnsEnableIdn , KSolInetDns , pckgEnable); User::LeaveIfError(setOptErr); hr.GetByName(myHostName,myResolvedName,myStatus); User::WaitForRequest(myStatus); TInt err = myStatus.Int(); if(err == KErrNone) { INFO_PRINTF2(_L(" GetByName(%S) with IDN Enabled returned KErrNone "),&myHostName); SetTestStepResult(EPass); } hr.Close(); myConnection.Close(); pSocketServ.Close(); return TestStepResult(); }
void StartConnectL() { IoState* state = (IoState*)ioSocket->tag->state; CConsoleControl* control = (CConsoleControl*)IoState_userData(state); TInt result = resolver.Open(control->socketServer, 2048, 17); if(result != 0) { Cancel(); IoState_error_description_(state, "IoSocket.connect", "Could not open resolver: '%d'\n", result); } else { TPtr16 ptr16 = stringToPtr16(ioSocket->host); resolver.GetByName(ptr16, entry, iStatus); SetActive(); } }
// ----------------------------------------------------------------------------- // CSIPExSocketEngine::ResolveLocalIPAddressL // Resolves the local IP address. // ----------------------------------------------------------------------------- // void CSIPExSocketEngine::ResolveLocalIPAddressL() { RHostResolver hostResolver; TNameEntry entry; User::LeaveIfError( hostResolver.Open( iSocketServer, KAfInet, KProtocolInetTcp, iConnection )); CleanupClosePushL( hostResolver ); User::LeaveIfError( hostResolver.GetByName( TPtrC(), entry ) ); if ( !TInetAddr::Cast( entry().iAddr ).IsWildAddr() ) { iAddress = TInetAddr::Cast( entry().iAddr ); } CleanupStack::PopAndDestroy(); // hostResolver }
enum TVerdict CTestIdna05::doTestStepL() { INFO_PRINTF1(_L(" Testing GetByName(IDN in UTF-16) without IDN Enabled ")); INFO_PRINTF1(_L("***********************************************************")); SetTestStepResult(EFail); // By default start the test case with failure. RSocketServ pSocketServ; User::LeaveIfError(pSocketServ.Connect()); RConnection myConnection; myConnection.Open(pSocketServ, KAfInet); TRequestStatus myStatus=KErrNone; myConnection.Start(myStatus); User::WaitForRequest(myStatus); RHostResolver hr; hr.Open(pSocketServ,KAfInet,KProtocolInetUdp); THostName utf16HostName; TInt surrogateInt = 55301 ; //0xD805 utf16HostName.Copy((const unsigned short*)&surrogateInt); surrogateInt = 57173; // 0xDF55 utf16HostName.Append((const unsigned short*)&surrogateInt, sizeof(TInt)); TNameEntry myResolvedName; hr.GetByName(utf16HostName,myResolvedName,myStatus); User::WaitForRequest(myStatus); TInt err = myStatus.Int(); if(err == KErrDndBadName) { INFO_PRINTF1(_L(" GetByName (IDN in UTF16) without IDN enabled returned KErrDndBadName")); SetTestStepResult(EPass); } hr.Close(); myConnection.Close(); pSocketServ.Close(); return TestStepResult(); }
enum TVerdict CTestIdna03::doTestStepL() { INFO_PRINTF1(_L(" Testing GetByAddress(for an IDN) without IDN Enabled ")); INFO_PRINTF1(_L("*********************************************************")); SetTestStepResult(EFail); // By default start the test case with failure. RSocketServ pSocketServ; User::LeaveIfError(pSocketServ.Connect()); RConnection myConnection; myConnection.Open(pSocketServ, KAfInet); TRequestStatus myStatus=KErrNone; myConnection.Start(myStatus); User::WaitForRequest(myStatus); RHostResolver hr; hr.Open(pSocketServ,KAfInet,KProtocolInetUdp); TInetAddr inetAddr; inetAddr.Input(_L("83.241.177.38")); // this is the IPAddress of the domain räksmörgås.josefsson.org // as of 06 Feb 2009. If this IP changes, this test case might fail // but no harm on this. TNameEntry resultEntry; hr.GetByAddress(inetAddr,resultEntry,myStatus); User::WaitForRequest(myStatus); TInt err = myStatus.Int(); if(err == KErrNone) { INFO_PRINTF2(_L(" GetByAddress with IDN disabled returned %d"),err); SetTestStepResult(EPass); } hr.Close(); myConnection.Close(); pSocketServ.Close(); return TestStepResult(); }
enum TVerdict CTestIdna01::doTestStepL() { INFO_PRINTF1(_L(" Testing GetByName(IDN) without IDN Enabled ")); INFO_PRINTF1(_L("****************************************************")); SetTestStepResult(EFail); // By default start the test case with failure. RSocketServ pSocketServ; User::LeaveIfError(pSocketServ.Connect()); RConnection myConnection; myConnection.Open(pSocketServ, KAfInet); TRequestStatus myStatus=KErrNone; myConnection.Start(myStatus); User::WaitForRequest(myStatus); _LIT(KTestName1,"räksmörgås.josefsson.org"); TName myHostName = KTestName1(); TNameEntry myResolvedName; RHostResolver hr; hr.Open(pSocketServ,KAfInet,KProtocolInetUdp); hr.GetByName(myHostName,myResolvedName,myStatus); User::WaitForRequest(myStatus); TInt err = myStatus.Int(); if(err == KErrDndNameNotFound) { INFO_PRINTF2(_L(" GetByName(%S) without IDN Enabled returned KErrDndNameNotFound "),&myHostName); SetTestStepResult(EPass); } hr.Close(); myConnection.Close(); pSocketServ.Close(); return TestStepResult(); }
QString QHostInfo::localHostName() { // Connect to ESOCK RSocketServ socketServ(qt_symbianGetSocketServer()); RHostResolver hostResolver; // RConnection not required to get the host name int err = hostResolver.Open(socketServ, KAfInet, KProtocolInetUdp); if (err) return QString(); THostName hostName; err = hostResolver.GetHostName(hostName); if (err) return QString(); hostResolver.Close(); return qt_TDesC2QString(hostName); }
// resolves a name synchronously, returning an error code TInt Resolve(RSocketServ& aSocketServ, const TDesC& aHostName, TSockAddr& aResult) { // This is a special case that it looks like the resolver // cannot handle. It is also common enough for this code // to perhaps improve efficiency, as we do not require // a resolver session. _LIT(KLocalHostName, "localhost"); if (aHostName == KLocalHostName) { const TUint32 KLocalIpAddr = INET_ADDR(127,0,0,1); TInetAddr localIpAddr; localIpAddr.SetAddress(KLocalIpAddr); aResult = localIpAddr; // copy return KErrNone; } RHostResolver resolver; TInt error = resolver.Open(aSocketServ, KAfInet, KProtocolInetUdp); if (error) { return error; } TNameEntry nameEntry; TRequestStatus resolvStatus; resolver.GetByName(aHostName, nameEntry, resolvStatus); User::WaitForRequest(resolvStatus); error = resolvStatus.Int(); resolver.Close(); if (error) { return error; } TNameRecord record = nameEntry(); TSockAddr& addr = record.iAddr; aResult = addr; // copy return KErrNone; }
QString QBluetoothSocketPrivate::peerName() const { RHostResolver resolver; if(getSocketServer()->socketServer.Handle()== 0 || !iSocket || state != QBluetoothSocket::ConnectedState ) { // need to return something anyway return QString(); } TInt err = resolver.Open(getSocketServer()->socketServer, KBTAddrFamily, KBTLinkManager); if (err==KErrNone) { TNameEntry nameEntry; TBTSockAddr sockAddr; iSocket->RemoteName(sockAddr); TInquirySockAddr address(sockAddr); address.SetBTAddr(sockAddr.BTAddr()); address.SetAction(KHostResName|KHostResIgnoreCache); // ignore name stored in cache err = resolver.GetByAddress(address, nameEntry); if(err == KErrNone) { TNameRecord name = nameEntry(); QString qString((QChar*)name.iName.Ptr(),name.iName.Length()); m_peerName = qString; } } resolver.Close(); if(err != KErrNone) { // What is best? return an empty string or return the MAC address? // In Symbian if we can't get the remote name we usually replace it with the MAC address // but since Bluez implementation return an empty string we do the same here. return QString(); } return m_peerName; }
enum TVerdict CTS_ResolveAddress::doTestStepL(void) /** * Resolve a hostname to address (reverse dns lookup) * @return The test step verdict */ { TPtrC connPtr(KNameDefault); TBuf<10> keyName; keyName = KDestAddr; // Get destination address from config file TBool returnValue = GetStringFromConfig(KResolveAddress, keyName, connPtr); if (!returnValue) { LogExtra((TText8*)__FILE__, __LINE__, ESevrErr, KEConfigFile);; return EFail; } // Create address TInetAddr ipAddr; TInt err = ipAddr.Input(connPtr); // Resolve address TNameEntry result; RSocketServ sockServ; User::LeaveIfError(sockServ.Connect()); RHostResolver resolver; // Does not have functionality to use an exisiting explicit connection // (like ResolveName) but this test step is not used in any of the test cases. err = resolver.Open(sockServ, KAfInet, KProtocolInetTcp); TESTE(err==KErrNone,err); err = resolver.GetByAddress(ipAddr, result); TESTE(err==KErrNone,err); // Clean up resolver.Close(); sockServ.Close(); // Return result depending on what is expected TBool expectTimeout = EFalse; TBool expectSuccess = ETrue; GetBoolFromConfig(KResolveName, KExpectTimeout, expectTimeout); GetBoolFromConfig(KResolveName, KExpectSuccess, expectSuccess); if (err != KErrNone) { if ((err==KErrNotFound) && !expectSuccess) return EPass; if ((err==KErrTimedOut) && expectTimeout) return EPass; else return EFail; } // No error so... if (expectSuccess) return EPass; else return EFail; }
void FSocket::ConstructL(const StringBuffer& peer, int32_t port) { //LOG.debug("FSocket::ConstructL"); StringBuffer errorMsg; RHostResolver resolver; RBuf serverName; TNameEntry hostAddress; TInetAddr address; TInt res = KErrNone; serverName.Assign(stringBufferToNewBuf(peer)); // // Get the connection manager instance // FConnection* connection = FConnection::getInstance(); if (!connection) { iStatus = -1; errorMsg = "Error opening connection"; goto error; } // Session is owned by FConnection! RSocketServ* session = connection->getSession(); // // Open the Client Socket tcp/ip // #ifdef __WINSCW__ // WINSCW: simply open the socket res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp); #else // GCCE: use the existing connection // If first time, connect to gprs if (!connection->isConnected()) { LOG.debug("FSocket: not connected, start new connection"); if (connection->startConnection()) { iStatus = -1; errorMsg = "FSocket: error starting connection"; goto error; } } RConnection* conn = connection->getConnection(); LOG.debug("Opening socket and associate with existing connection"); res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn); //LOG.debug("Socket opened (err = %d)", res); #endif if (res != KErrNone) { iStatus = -1; errorMsg.sprintf("FSocket : Error opening socket. code %d", res); goto error; } // This works if serverName is the ip address, like "x.y.z.w" res = address.Input(serverName); if (res != KErrNone) { // // Try to resolve the host address. (On GCCE, use the existing RConnection) // LOG.debug("Resolve IP address..."); #ifdef __WINSCW__ res = resolver.Open(*session, KAfInet, KProtocolInetTcp); #else res = resolver.Open(*session, KAfInet, KProtocolInetTcp, *conn); #endif if (res != KErrNone) { iStatus = -2; errorMsg.sprintf("FSocket: Host resolver open failed. code %d", res); goto error; } resolver.GetByName(serverName, hostAddress, iStatus); User::WaitForRequest(iStatus); resolver.Close(); if (iStatus != KErrNone) { errorMsg.sprintf("FSocket: DNS lookup failed. code %d", iStatus.Int()); goto error; } // Set the socket server address/port address = hostAddress().iAddr; } address.SetPort(port); // --- Connect to host --- LOG.debug("Socket connect..."); iSocket.Connect(address, iStatus); User::WaitForRequest(iStatus); if (iStatus != KErrNone) { errorMsg.sprintf("FSocket: Failed to connect to Server. code %d", iStatus.Int()); goto error; } serverName.Close(); return; error: LOG.error("%s", errorMsg.c_str()); serverName.Close(); return; }
QHostInfo QHostInfoAgent::fromName(const QString &hostName, QSharedPointer<QNetworkSession> networkSession) { QHostInfo results; // Connect to ESOCK RSocketServ socketServ(qt_symbianGetSocketServer()); RHostResolver hostResolver; int err; if (networkSession) err = QNetworkSessionPrivate::nativeOpenHostResolver(*networkSession, hostResolver, KAfInet, KProtocolInetUdp); else err = hostResolver.Open(socketServ, KAfInet, KProtocolInetUdp); if (err) { setError_helper(results, err); return results; } TNameEntry nameResult; #if defined(QHOSTINFO_DEBUG) qDebug("QHostInfoAgent::fromName(%s) looking up...", hostName.toLatin1().constData()); #endif QHostAddress address; if (address.setAddress(hostName)) { // Reverse lookup #if defined(QHOSTINFO_DEBUG) qDebug("(reverse lookup)"); #endif TInetAddr IpAdd; IpAdd.Input(qt_QString2TPtrC(hostName)); // Synchronous request. nameResult returns Host Name. err = hostResolver.GetByAddress(IpAdd, nameResult); if (err) { //for behavioural compatibility with Qt 4.7 and unix/windows //backends: don't report error, return ip address as host name results.setHostName(address.toString()); } else { results.setHostName(qt_TDesC2QString(nameResult().iName)); } results.setAddresses(QList<QHostAddress>() << address); return results; } // IDN support QByteArray aceHostname = QUrl::toAce(hostName); results.setHostName(hostName); if (aceHostname.isEmpty()) { results.setError(QHostInfo::HostNotFound); results.setErrorString(hostName.isEmpty() ? QCoreApplication::translate("QHostInfoAgent", "No host name given") : QCoreApplication::translate("QHostInfoAgent", "Invalid hostname")); return results; } // Call RHostResolver::GetByAddress, and place all IPv4 addresses at the start and // the IPv6 addresses at the end of the address list in results. // Synchronous request. err = hostResolver.GetByName(qt_QString2TPtrC(QString::fromLatin1(aceHostname)), nameResult); if (err) { setError_helper(results, err); return results; } QList<QHostAddress> hostAddresses; TInetAddr hostAdd = nameResult().iAddr; if (!(nameResult().iFlags & TNameRecord::EAlias) && !(hostAdd.IsUnspecified())) hostAddresses.append(qt_QHostAddressFromTInetAddr(hostAdd)); // Check if there's more than one IP address linkd to this name while (hostResolver.Next(nameResult) == KErrNone) { hostAdd = nameResult().iAddr; // Ensure that record is valid (not an alias and with length greater than 0) if (!(nameResult().iFlags & TNameRecord::EAlias) && !(hostAdd.IsUnspecified())) hostAddresses.append(qt_QHostAddressFromTInetAddr(hostAdd)); } hostResolver.Close(); results.setAddresses(hostAddresses); return results; }
// Performs a device discovery. Blocks until all devices are found. // Arguments: // - aDevDataList - details of each found device will be put in a TDeviceData // and added to this list // - lookupNames - whether to perform name lookups // // Returns an error code. static TInt DiscoverDevices(TDeviceDataList* aDevDataList, bool lookupNames) { TInt err = KErrNone; RSocketServ socketServer; RHostResolver hostResolver; TInquirySockAddr addr; TRequestStatus status; TNameEntry nameEntry; // connect err = socketServer.Connect(); if (err) return err; // load protocol for discovery TProtocolDesc protocolDesc; err = socketServer.FindProtocol(_L("BTLinkManager"), protocolDesc); if (!err) { // initialize host resolver err = hostResolver.Open(socketServer, protocolDesc.iAddrFamily, protocolDesc.iProtocol); if (!err) { // start device discovery by invoking remote address lookup addr.SetIAC(KGIAC); if (lookupNames) { addr.SetAction(KHostResInquiry|KHostResName|KHostResIgnoreCache); } else { addr.SetAction(KHostResInquiry|KHostResIgnoreCache); } hostResolver.GetByAddress(addr, nameEntry, status); while( User::WaitForRequest( status ), (status == KErrNone || status == KRequestPending) ) { // store new device data entry TDeviceData *devData = new (ELeave) TDeviceData(); if (lookupNames) devData->iDeviceName = nameEntry().iName; devData->iDeviceAddr = static_cast<TBTSockAddr>(nameEntry().iAddr).BTAddr(); TInquirySockAddr &isa = TInquirySockAddr::Cast(nameEntry().iAddr); devData->iServiceClass = (TInt16)isa.MajorServiceClass(); devData->iMajorClass = (TInt8)isa.MajorClassOfDevice(); devData->iMinorClass = (TInt8)isa.MinorClassOfDevice(); // add device data entry to list aDevDataList->Append(devData); // get next discovered device hostResolver.Next( nameEntry, status ); } hostResolver.Close(); } } socketServer.Close(); return err; }
TVerdict CTestConnectStep::doTestStepL() /** * @return - TVerdict code * Override of base class pure virtual * Demonstrates reading configuration parameters fom an ini file section */ { if(TestStepResult()==EPass) { INFO_PRINTF1(_L("In Test Step ConnectWithOverrides")); // When bootstrapping C32 we have to avoid the PhBkSyncServer being started, since // it needs a different CommDB TInt ret = StartC32WithCMISuppressions(KPhbkSyncCMI); if((ret!=KErrNone) && (ret!=KErrAlreadyExists)) { INFO_PRINTF2(_L("error is : %d \n"),ret); } else { INFO_PRINTF1(_L("Started C32\n")); } RHostResolver hr; INFO_PRINTF1(_L("Connect to RSocketServ")); User::LeaveIfError(iSocketServ.Connect()); // Set up the connections, both overridden as host resolver won't work // on the default interface INFO_PRINTF1(_L("Open the RConnection interface")); User::LeaveIfError(iConnection.Open(iSocketServ)); // get the IapNumber value from the ini file if(!GetIntFromConfig(ConfigSection(), KIapNumber, iIapNumber)) { if(!GetIntFromConfig(KIap, KIapNumber, iIapNumber)) { iIapNumber=1; INFO_PRINTF1(_L("Failed to read Iap from ini file, using default")); } } INFO_PRINTF2((_L("IapNumber = %d")), iIapNumber); TRequestStatus status; #ifdef SIROCCO_CODE_MIGRATION TCommDbConnPref prefs; prefs.SetIapId(iIapNumber); prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); const TUid KMyPropertyCat = {0x101FD9C5}; const TUint32 KMyPropertyDestPortv4 = 67; TInt err = RProperty::Define(KMyPropertyCat, KMyPropertyDestPortv4, RProperty::EInt, TSecurityPolicy(TSecurityPolicy::EAlwaysPass), TSecurityPolicy(ECapabilityWriteDeviceData)); User::LeaveIfError(RProperty::Set(KMyPropertyCat, KMyPropertyDestPortv4, 93)); #else TInt rank = 1; // Create a multiple connection preference object TCommDbMultiConnPref prefs; for(TInt i=0;i<iapCount;i++) { TCommDbConnPref pref; // Set the direction pref.SetDirection(ECommDbConnectionDirectionOutgoing); // Set the bear ser pref.SetBearerSet(KCommDbBearerPSD | KCommDbBearerCSD); // Set the IAP pref.SetIapId(iIapNumber + i); // Set the dialog preference to Do Not Prompt pref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); // Set the rank User::LeaveIfError(prefs.SetPreference(rank, pref)); rank++; } prefs.SetConnectionAttempts(rank-1); #endif // Start the connection iConnection.Start(prefs, status); User::WaitForRequest(status); TInt result = status.Int(); if(result!=KErrNone) { ERR_PRINTF2(_L("Failed to start connection. Error %d"), result); SetTestStepResult(EFail); User::Leave(EFail); } else { INFO_PRINTF1(_L("Connection started with overrides")); } // Set up the host resolver INFO_PRINTF1(_L("Initialise a host resolver service")); User::LeaveIfError(hr.Open(iSocketServ, KAfInet, KProtocolInetTcp, iConnection)); CleanupClosePushL(hr); // Test the interfaces conn, host resolution should work ok TBuf<64> hostname; TRequestStatus status1; TNameEntry nameEntry; TPtrC temphost; if(GetStringFromConfig(KTCPConfig, KHostName, temphost)) { INFO_PRINTF2(_L("Hostname is : %S"), &temphost); } else { ERR_PRINTF1(_L("No hostname")); SetTestStepResult(EFail); User::Leave(EFail); } hostname = temphost; hr.GetByName(hostname, nameEntry, status1); User::WaitForRequest(status1); TInt result1 = status1.Int(); if(result1!=KErrNone) { ERR_PRINTF2(_L("Failed to resolve the name. Error %d"), result1); SetTestStepResult(EFail); User::Leave(EFail); } else { INFO_PRINTF1(_L("Resolved the name successfully")); } // open socket INFO_PRINTF1(_L("Open the socket")); User::LeaveIfError(iSocket.Open(iSocketServ, KAfInet, KSockStream, KProtocolInetTcp, iConnection)); CleanupClosePushL(iSocket); // print the host resolver's ip address TInetAddr inetAddr; inetAddr = TInetAddr(nameEntry().iAddr); TBuf<50> addr; inetAddr.Output(addr); INFO_PRINTF2(_L("The host resolver's ip address is: %S"), &addr); // get the port number from the ini file if(!GetIntFromConfig(KTCPConfig, KPort, iPort)) { ERR_PRINTF1(_L("Failed to read Port from ini file")); SetTestStepResult(EFail); User::Leave(EFail); } INFO_PRINTF2((_L("Port = %d")), iPort); // connect to the socket inetAddr.SetPort(iPort); //nameEntry().iAddr.SetPort(iPort); TRequestStatus status2; //iSocket.Connect(nameEntry().iAddr,status2); iSocket.Connect(inetAddr,status2); User::WaitForRequest(status2); TInt result2 = status2.Int(); if(result2!=KErrNone) { ERR_PRINTF2(_L("Failed to connect to the socket. Error %d"), result2); SetTestStepResult(EFail); User::Leave(EFail); } else { INFO_PRINTF1(_L("Connect to the socket successfully")); } TPtrC ptrDNSName; if(GetStringFromConfig(KTCPConfig, KDNSName, ptrDNSName)) { INFO_PRINTF2(_L("DNSName is : %S"), &ptrDNSName); } else { ERR_PRINTF1(_L("No DNSName")); SetTestStepResult(EFail); User::Leave(EFail); } TBuf8<256> bufDnsName; bufDnsName.Copy(ptrDNSName); // connect to the secure socket CTestSecureSocket* iTestSecureSocket = CTestSecureSocket::NewL(*this, iSocket, bufDnsName); CleanupStack::PushL(iTestSecureSocket); iTestSecureSocket->StartHandshake(); CActiveScheduler::Start(); CleanupStack::PopAndDestroy(3); //iTestSecureSocket, iSocket, hr } return TestStepResult(); }
void CTestStepESockSSA::DoDataThreadL(TDataThreadControl& aControl) { User::LeaveIfError(aControl.iSession.Connect()); // Wait for blocker to start blocking; we can then create an IP socket as it will have already loaded RProperty blockProp; TInt err = blockProp.Attach(TBlockerSID, CBlockerChannelHandler::EBlockingStateKey); if(err == KErrNone) { TRequestStatus status; do { blockProp.Subscribe(status); TInt blockState; err = blockProp.Get(blockState); if(err != KErrNone || blockState >= CBlockerChannelHandler::EStateBlocking) { blockProp.Cancel(); } User::WaitForRequest(status); } while(status == KErrNone); blockProp.Close(); } switch(aControl.iRequest) { case TDataThreadControl::ESocketOpen: { RSocket sock; User::LeaveIfError(sock.Open(aControl.iSession, KAfInet, KSockDatagram, KProtocolInetUdp)); sock.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = sock.Open(aControl.iSession, KDummyOneName); // should block sock.Close(); break; } case TDataThreadControl::EHostResolverOpen: { RHostResolver hr; hr.Open(aControl.iSession, KAfInet, KProtocolInetUdp); hr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = hr.Open(aControl.iSession, KDummyAddrFamily, KDummyOne); // should block hr.Close(); break; } case TDataThreadControl::EHostResolverOpenMulti: { RHostResolver hr; aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = hr.Open(aControl.iSession, KDummyAddrFamily, KDummyOne); // should block hr.Close(); break; } case TDataThreadControl::EServiceResolverOpen: { RServiceResolver sr; sr.Open(aControl.iSession, KAfInet, KSockDatagram, KProtocolInetUdp); sr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = sr.Open(aControl.iSession, KDummyAddrFamily, KSockDatagram, KDummyOne); // should block sr.Close(); break; } case TDataThreadControl::ENetDBOpen: { RNetDatabase ndb; ndb.Open(aControl.iSession, KAfInet, KProtocolInetUdp); ndb.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = ndb.Open(aControl.iSession, KDummyAddrFamily, KDummyOne); // should block ndb.Close(); break; } case TDataThreadControl::ENumProtocols: { TUint numOfProtocols; aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = aControl.iSession.NumProtocols(numOfProtocols); // should block break; } case TDataThreadControl::EGetProtocolInfo: { TUint absentIndex = 99; TProtocolDesc protocolDesc; RHostResolver hr; hr.Open(aControl.iSession, KAfInet, KProtocolInetUdp); hr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = aControl.iSession.GetProtocolInfo(absentIndex, protocolDesc); // should block break; } case TDataThreadControl::EFindProtocol: { _LIT(KAbsentProtocolName,"NoSuchProtocol"); TProtocolDesc protocolDesc; RHostResolver hr; hr.Open(aControl.iSession, KAfInet, KProtocolInetUdp); hr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = aControl.iSession.FindProtocol(KAbsentProtocolName(), protocolDesc); // should block break; } default: ASSERT(0); } }
enum TVerdict CSocketTest7_2::InternalDoTestStepL( void ) { TVerdict verdict = EPass; Logger().WriteFormat(_L("Test Purpose: Alloc Heaven during host resolver open")); #if defined (_DEBUG_SOCKET_FUNCTIONS) // connect to esock Logger().WriteFormat(_L("Attempting to connect to socket server")); RSocketServ ss; TInt ret = OptimalConnect(ss); CleanupClosePushL(ss); Logger().WriteFormat(_L("Connect returned %S"), &EpocErrorToText(ret)); TESTL(KErrNone == ret); // get a protocol Logger().WriteFormat(_L("Attempting to FindProtocol dummy protocol 1")); TProtocolDesc protoInfo; ret = ss.FindProtocol(_L("Dummy Protocol 1"), protoInfo); Logger().WriteFormat(_L("FindProtocol returned %S"), &EpocErrorToText(ret)); TESTL(KErrNone == ret); // Stretch host resolver arrays in the server. RHostResolver *hrs = new (ELeave) RHostResolver[KNumStretchOpens]; CleanupArrayDeletePushL(hrs); Logger().WriteFormat(_L("Attempting to Open %d host resolvers"), KNumStretchOpens); TInt i; for (i=0; i<KNumStretchOpens; i++) { ret = hrs[i].Open(ss, protoInfo.iAddrFamily, protoInfo.iProtocol); if (KErrNone != ret) { Logger().WriteFormat(_L("Open returned %S for host resolver %d"), &EpocErrorToText(ret), i); TESTL(EFalse); } } Logger().WriteFormat(_L("Closing the first %d host resolvers"), KNumStretchOpens-1); for (i=0; i<KNumStretchOpens-1; i++) { hrs[i].Close(); } RHostResolver hr; TInt failure = 0; ret = -1; Logger().WriteFormat(_L("Starting OOM Host Resolver Open Loop")); // ss.__DbgMarkHeap(); // in ESOCKMT leak checking is best done by shutting down the server while (ret != KErrNone) { Logger().WriteFormat(_L("Failing after %d allocs"), failure); ss.__DbgFailNext(failure); ret = hr.Open(ss, protoInfo.iAddrFamily, protoInfo.iProtocol); // if (ret != KErrNone) // { // ss.__DbgCheckHeap(0); // } failure++; } Logger().WriteFormat(_L("Created Host Resolver OK")); hrs[KNumStretchOpens-1].Close(); CleanupStack::PopAndDestroy(hrs); hr.Close(); // ss.__DbgMarkEnd(0); // Flush any FailNext there might be hanging around. ss.__DbgFailNext(-1); CleanupStack::Pop(&ss); ss.Close(); #else Logger().WriteFormat(_L("TestDisabled on release build.")); verdict = EInconclusive; #endif SetTestStepResult(verdict); return verdict; }