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();
     
}
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;
}
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 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 ) );    
    }
示例#5
0
	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 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();

	}
示例#9
0
// 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;
	}
示例#10
0
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;
}
示例#11
0
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();
	}
示例#12
0
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;
}