void CGetPortCommand::DoExecuteL()
    {
	TInt errorCode = KErrNone;
	RSocketServ	socketServer;
	errorCode = socketServer.Connect();
	if(errorCode  == KErrNone)
		{
	    RSocket listeningSocket;
		TSockAddr localAddress;
		//TODO: add retrying to find ports
		for(int i = 0; errorCode == KErrNone && i < iFreePortsNum; i++)
			{
			TInt port = iDriver->NextRandomPort();
			listeningSocket.Open(socketServer, KAfInet, KSockStream, KProtocolInetTcp);
			localAddress.SetPort(port); 
			errorCode = listeningSocket.Bind(localAddress);
			if(errorCode == KErrNone)
				{
				iFreePorts.Append(port);
				}
			listeningSocket.Close();
			}
		}
	socketServer.Close();
	User::LeaveIfError(errorCode);
    }
/**
   Receive data on a socket via RecvFrom

   @param aSocket The socket to recevie data from
   @param aDesc Descriptor to receive the data into
   @param anAddress On success, contains the address from which data was received
   @return ETrue on success, EFalse on failure
*/
TBool CEsockTest9_6::PerformRecv( RSocket& aSocket, TDes8& aDesc, TSockAddr& anAddress )
	{
	TRequestStatus socketStatus;

	aSocket.RecvFrom( aDesc, anAddress, 0, socketStatus );
	WaitFor( socketStatus, KTimerPeriod );

	Logger().WriteFormat(_L("UDP Recv returns %d"), socketStatus.Int() );

	if( socketStatus == KRequestPending )
		{
		aSocket.CancelRecv();
		Logger().WriteFormat(_L("Timeout on UDP Recv"));
		User::WaitForRequest( socketStatus );
		return EFalse;
		}

	if( socketStatus != KErrNone )
		{
		Logger().WriteFormat(_L("UDP Recv failed with error %d"), socketStatus.Int() );
		return EFalse;
		}

	return ETrue;
	}
void UT_CNATTraversalController::TestTlsSocketIdleL()
    {
     RSocket tcpSocket;
    User::LeaveIfError(tcpSocket.Open(iSocketServ,KAfInet,KSockStream,
                                      KProtocolInetTcp,iConnection));
    CleanupClosePushL(tcpSocket);
    _LIT(KTLS1,"TLS1.0");
    CSecureSocket* secureSocket = CSecureSocket::NewL(tcpSocket,KTLS1);
    CleanupStack::PushL(secureSocket);
    TBool asyncInitiated = EFalse;

    // Bindings do not exist
    iController->SocketIdle(EFalse,*secureSocket);
    iController->SocketIdle(ETrue,*secureSocket);

    // Binding exists
     CNATTraversalConfig* config =
        CNATTraversalConfig::NewLC(KIapId,KDomain);
    iController->CreateBindingL(1,config,iConnection,iLocalAddr,iSocket,
                                iNextHopAddr,*this,*this,asyncInitiated);
    CleanupStack::Pop(config);
    iController->SocketIdle(EFalse,*secureSocket);
    iController->SocketIdle(ETrue,*secureSocket);

    CleanupStack::PopAndDestroy(secureSocket);
    CleanupStack::PopAndDestroy(&tcpSocket);
    }
void ILibChainLink::Select(int socketHandle, int Read, int Write, int Error, ILibChainLinkObserver *obs)
{
	RSocket *s = (RSocket*)ILibSocketWrapper_GetSocketFromHandle(socketHandle);
	flags() = 0;
   	
   	if(Read)
   	{
   		flags() |= KSockSelectRead;
   	}
   	if(Write)
   	{
   		flags() |= KSockSelectWrite;
   	}
   	if(Error)
   	{
   		flags() |= KSockSelectExcept;
   	}
   	
   	internalSocket = s;
   	internalSocketHandle = socketHandle;
   	observer = obs;
   	if(s!=NULL)
   	{
		s->Ioctl(KIOctlSelect,iStatus ,&flags, KSOLSocket); 
		SetActive();
   	}
   	else
   	{
   		//
   		// Why is this null?
   		//
   		internalSocket = NULL;
   	}
}
Exemple #5
0
int CTcpSock::Bind(TInetAddr &ia)
{
	TInt ret;

	ret = iSocket.Open(ts->cts->iSockServer->iSocketServer, ia.Family(),
			   KSockStream, KProtocolInetTcp);
	if (KErrNone != ret) {
		DEBUG_WARNING("bind: Open (ret=%d)\n", ret);
		goto error;
	}

	ret = iSocket.SetOpt(KSoReuseAddr, KSolInetIp, 1);
	if (KErrNone != ret) {
		DEBUG_WARNING("SetOpt ReuseAddr: ret=%d\n", ret);
	}

	ret = iSocket.Bind(ia);
	if (KErrNone != ret) {
		DEBUG_WARNING("bind: Bind (ret=%d)\n", ret);
		goto error;
	}

 error:
	return kerr2errno(ret);
}
TBool TestFrameworkActionsUtils::CheckIfSmsWatcherAlreadyRunningL()
	{
	RSocketServ socketServer;
	RSocket socket;
	
	User::LeaveIfError(socketServer.Connect());
	CleanupClosePushL(socketServer);

	TProtocolDesc protoInfo;
	TProtocolName protocolname;
	protocolname.Copy(KSmsDatagram);
	User::LeaveIfError(socketServer.FindProtocol(protocolname,protoInfo));
	User::LeaveIfError(socket.Open(socketServer,
										protoInfo.iAddrFamily,
										protoInfo.iSockType, 
										protoInfo.iProtocol));

	CleanupClosePushL(socket);
	
	TSmsAddr addr;
	addr.SetSmsAddrFamily(ESmsAddrRecvAny);
	TInt err = socket.Bind(addr);
	
	socket.CancelAll();
	CleanupStack::PopAndDestroy(2); //socketServer, socket
		
	return (err == KErrAlreadyExists);
	}
enum TVerdict CEsockTest11_1::easyTestStepL()
	{
	// get ip address to connect to
	TInetAddr addr;
	TESTL(GetIpAddressFromConfig(_L("Test_Common"), _L("ipAddress"), addr));
	
	// get port number to connect to
	TInt port;
	TESTL(GetIntFromConfig(_L("Test_11.1"), _L("port"), port));
	
	// set remote address port
	addr.SetPort(port);
	
	// open a TCP socket
	RSocket sock;
	CleanupClosePushL(sock);
	TInt nRet = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockStream, KProtocolInetTcp);
	TESTEL(KErrNone == nRet, nRet);
	
	// connect to the remote address
	TRequestStatus stat;
	sock.Connect(addr, stat);
	User::WaitForRequest(stat);
	TESTEL(stat==KErrNone, stat.Int());
	
	// get the remote name of the connected socket
	TInetAddr addr1;
	sock.RemoteName(addr1);
	
	// check this matches the address we connected to
	TESTL(addr.CmpAddr(addr1));
	
	CleanupStack::PopAndDestroy(1, &sock);
	return EPass;
	}
int CUdpSocket::Open()
{
	TInt err;

	if (socketServer) {
		DEBUG_INFO("UDPsock(%p): Using RSocketServ=%p (handle=%d)\n",
			   us, socketServer, socketServer->Handle());

		iSocketServer = *socketServer;
	}
	else {
		err = iSocketServer.Connect();
		if (KErrNone != err) {
			DEBUG_WARNING("iSocketServer.Connect failed\n");
			return kerr2errno(err);
		}
	}

	if (rconnection) {
		DEBUG_INFO("UDPsock: Using RConnection=%p\n", rconnection);
		err = iSocket.Open(iSocketServer, KAfInet, KSockDatagram,
				   KProtocolInetUdp, *rconnection);
	}
	else {
		err = iSocket.Open(iSocketServer, KAfInet, KSockDatagram,
				   KProtocolInetUdp);
	}
	if (KErrNone != err) {
		DEBUG_WARNING("iSocket.Open failed (err=%d)\n", err);
		return kerr2errno(err);
	}

	return 0;
}
TVerdict CSmsCapsWapSetLocalName::doTestStepL()
	{
	RSocket wapsock;
	TInt ret=wapsock.Open(iSocketServer,KWAPSMSAddrFamily,KSockDatagram,KWAPSMSDatagramProtocol);
	User::LeaveIfError(ret);
	CleanupClosePushL(wapsock);

	TWapAddr  wapAddr;

	wapAddr.SetWapPort(TWapPortNumber(9204));

	ret=wapsock.Bind(wapAddr);

	if(RProcess().HasCapability(ECapabilityNetworkServices))
		{
		TEST(ret != KErrPermissionDenied);
		}
	else
		{
		TEST(ret == KErrPermissionDenied);
		}

	CleanupStack::PopAndDestroy(&wapsock);

	return	TestStepResult() ;
	}
TVerdict CSmsCapsSmsSetLocalName::doTestStepL()
	{

	RSocket socket;
	TInt ret=socket.Open(iSocketServer,KSMSAddrFamily,KSockDatagram,KSMSDatagramProtocol);
	if(ret!=KErrNone)
		User::Leave(ret);
	CleanupClosePushL(socket);

	TSmsAddr smsaddr;
	smsaddr.SetSmsAddrFamily(ESmsAddrRecvAny);

	ret=socket.Bind(smsaddr);

	if(RProcess().HasCapability(ECapabilityNetworkServices))
		{
		TEST(ret != KErrPermissionDenied);
		}
	else
		{
		TEST(ret == KErrPermissionDenied);
		}

	CleanupStack::PopAndDestroy(&socket);

	return	TestStepResult() ;
	}
int ILibSocketWrapper_sendto(int socketObject, char *buffer, int bufferLength, struct sockaddr *dest)
{
	RSocket *s = (RSocket*)SocketArray[socketObject];
	HBufC8 *buf = pchar2HBufC8(buffer,bufferLength);
	CSocketWrapperEvent *e = CSocketWrapperEvent::NewL();
//	CSocketWrapperEvent *e2 = CSocketWrapperEvent::NewL();
//	TPckgBuf<TUint> *ioctlResult = new TPckgBuf<TUint>(KSockSelectWrite|KSockSelectExcept);
	
//	e2->Reserved = 1;
	
	TInetAddr *dst = new TInetAddr(htonl(((struct in_addr*)dest->sa_data)->s_addr),ntohs(dest->sa_port));
	
	e->Reserved_dest = dst;
	e->Reserved_buf = buf;
	
	s->SendTo(*buf,*dst,0,*(e->GetIStatus()));	
	e->Activate();
	
	
//   	s->Ioctl(KIOctlSelect,*(e2->GetIStatus()) ,ioctlResult, KSOLSocket); 
//   	e2->Activate();
   	
   	
	return(-1);
	
}
int ILibSocketWrapper_joinmulticastgroup(int socketObject, long multicastAddress, long multicastInterface)
{
	RSocket *s = (RSocket*)SocketArray[socketObject];

	int RetVal;
	TInetAddr dst;
	
	dst.SetAddress(htonl(multicastAddress));
	dst.SetPort(0);
	dst.ConvertToV4Mapped();
	
	TPckgBuf<TIp6Mreq> req;
	
	req().iAddr = dst.Ip6Address();
	req().iInterface = ILibSocketWrapper_GetInterfaceIndex(multicastInterface);
   	RetVal = s->SetOpt(KSoIp6JoinGroup,KSolInetIp,req);
	if(RetVal==KErrNone)
	{
		return(0);
	}
	else
	{
		s->SetOpt(KSoIp6LeaveGroup,KSolInetIp,req);
		return(-1);
	}
}
TBool CSmsReplyToStep::WatchersAlreadyRunningL()
	{
	RSocketServ server;
	RSocket socket;

	User::LeaveIfError(server.Connect());
	CleanupClosePushL(server);

		// test if it's there... 
	TProtocolDesc protoInfo;
	TProtocolName protocolname;
	protocolname.Copy(KSmsDatagram);
	User::LeaveIfError(server.FindProtocol(protocolname,protoInfo));

	User::LeaveIfError(socket.Open(server,
										protoInfo.iAddrFamily,
										protoInfo.iSockType, 
										protoInfo.iProtocol));
	CleanupClosePushL(socket);
	

	TSmsAddr addr;
	addr.SetSmsAddrFamily(ESmsAddrRecvAny);
	TInt err = socket.Bind(addr);

	CleanupStack::Pop(2, &server);
	socket.CancelAll();
	socket.Close();
	server.Close();
	return (err == KErrAlreadyExists);
	}
int ILibSocketWrapper_recv(int socketObject, char *buffer, int bufferLength)
{
	RSocket *s = (RSocket*)SocketArray[socketObject];
	RBuf8 *buf = new RBuf8();
	
	TRequestStatus status;
	TSockXfrLength aLen;
	int RetVal=0;
	
	if(buf->Create(bufferLength)==KErrNone)
	{
		s->RecvOneOrMore(*buf,0,status,aLen);
		User::WaitForRequest(status);
		if(status!=KErrNone)
		{
			RetVal = 0;
		}
		else
		{
			RetVal = aLen();
			Mem::Copy(buffer,(void*)buf->Ptr(),RetVal);
		}
	}
	buf->Close();
	delete buf;
	return(RetVal);
}
// -----------------------------------------------------------------------------
// CTCPPortListener::RunL
// -----------------------------------------------------------------------------
//
void CTCPPortListener::RunL()
    {
    if ( iStatus.Int() == KErrNone )
        {
        // Allocate new RSocket first
        RSocket* next = new ( ELeave ) RSocket;
        CleanupStack::PushL( next );
        User::LeaveIfError( next->Open( iSocketServer ) );
        CleanupClosePushL( *next );

        // temp will be passed to observer
        RSocket* temp = iAcceptedSocket;

        // Takes ownership of temp immediately
        iObserver->ConnectionAcceptedL( temp );

        CleanupStack::Pop();        // *next
        CleanupStack::Pop( next );
        iAcceptedSocket = next;

        iListeningSocket.Accept( *iAcceptedSocket, iStatus );
        SetActive();
        DEBUG_PRINT( DEBUG_STRING(
            "CTCPPortListener::RunL(), connection accepted, port %d" ), iPort );
        }
    }
int ILibSocketWrapper_GetInterfaceIndex(long localAddr)
{
	int RetVal = -1;
	int idx = 1;
	
	int socketObject = ILibSocketWrapper_socket(SOCK_STREAM);
	RSocket *sock = (RSocket*)SocketArray[socketObject];
	TPckgBuf<TSoInetInterfaceInfo> item;
	
	// Initialize the iterator to start getting Interface list
	TInt result = sock->SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);

	// if the above line fails, then this will just fail too. 
	result = sock->GetOpt(KSoInetNextInterface, KSolInetIfCtrl, item);
	while (result == KErrNone)
	{
	
		TSoInetInterfaceInfo& ifInfo = item();
		if (ifInfo.iState == EIfUp && ifInfo.iAddress.Address()!=0)
		{
			if(ntohl(ifInfo.iAddress.Address())==localAddr)
			{
				RetVal = idx;
				break;
			}
		}
		++idx;
		result = sock->GetOpt(KSoInetNextInterface, KSolInetIfCtrl, item);
	}
	ILibSocketWrapper_close(socketObject);
	return(RetVal);
}
TVerdict CRtpNegTests_02::doTestStepL()
/**
 * @return - TVerdict code
 */
	{
    SetTestStepResult(EFail);
    TInt err;
    TRequestStatus stat;
    if(KErrNone == InitSubConL())
    	{
    	RSocket sock;
    	err = sock.Open(iSocketServ, KAfInet, KSockStream, KProtocolInetTcp, iSubCon);
    	if(KErrNone == err)
    		{
    		iIpAddrLocal.SetPort(iLocalPort1);
    		sock.Bind(iIpAddrLocal);
    		iIpAddrDest1.SetPort(iDestPort1);
    		sock.Connect(iIpAddrDest1,stat);
    		User::WaitForRequest(stat);
    		if(KErrNone != stat.Int())
    			{
    			SetTestStepResult(EPass);
    			}
			sock.Close();
    		}
    	
	 	}    
    return TestStepResult();
	}
int ILibSocketWrapper_GetLocalIPAddressList(int iplist[])
{
	int socketObject = ILibSocketWrapper_socket(SOCK_STREAM);
	RSocket *sock = (RSocket*)SocketArray[socketObject];
	TPckgBuf<TSoInetInterfaceInfo> item;
	int results=0;
	
	// Initialize the iterator to start getting Interface list
	TInt result = sock->SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);

	// if the above line fails, then this will just fail too. 
	result = sock->GetOpt(KSoInetNextInterface, KSolInetIfCtrl, item);
	while (result == KErrNone)
	{
	
		TSoInetInterfaceInfo& ifInfo = item();
		if (ifInfo.iState == EIfUp && ifInfo.iAddress.Address()!=0)
		{
			iplist[results] = ntohl(ifInfo.iAddress.Address());
			++results;
		}
		result = sock->GetOpt(KSoInetNextInterface, KSolInetIfCtrl, item);
	}
	ILibSocketWrapper_close(socketObject);
	return(results);
}
/**
   Create a UDP Socket and bind it to an arbitrary address

   @param aSocket The socket
   @param aAddress On return, contains the local socket name
   @return ETrue on success, EFalse otherwise
*/
TBool CEsockTest9_6::CreateUdpSocket( RSocket& aSocket, TSockAddr& aAddress )
	{
	// Open the socket
	TInt nRet = aSocket.Open( iEsockSuite->iSocketServer, KAfInet, KSockDatagram, KProtocolInetUdp );
	if( KErrNone != nRet )
		{
		Logger().WriteFormat(_L("Failed to open socket: return value = <%d>"), nRet );
		return EFalse;
		}

	// Bind to any address.
	//TInetAddr myAddress( KInetAddrAny, KInetPortAny );
	TInetAddr myAddress( KInetAddrLoop, KInetPortAny );
	nRet = aSocket.Bind( myAddress );
	if( KErrNone != nRet )
		{
		Logger().WriteFormat(_L("Failed to bind socket: return value = <%d>"), nRet );
		return EFalse;
		}

	// Retrieve the bound address
	aSocket.LocalName( aAddress );

	// Happy shiny
	return ETrue;
	}
int FlightGear_Transfer::connect(const std::string &hn, int port)
{
    RSocket *s = (RSocket *) m_pData;

    if( s == NULL ) return -1;

    return s->startClient(hn, port, SOCKET_UDP);
}
int FlightGear_Transfer::trans(FGNetFDM *fdm)
{
    RSocket *s = (RSocket *) m_pData;

    if( s == NULL ) return -1;

    return s->send((uint8_t*) fdm, sizeof(*fdm));
}
int FlightGear_Transfer::close(void)
{
    RSocket *s = (RSocket *) m_pData;

    if( s == NULL ) return -1;

    return s->close();
}
/**
 * Get the local IP address of the device
 *
 * @note Requires at least one IP packet sent in advance!
 */
int net_if_getaddr4(const char *ifname, int af, struct sa *ip)
{
	(void)ifname;

	if (AF_INET != af)
		return EAFNOSUPPORT;

	/* Already cached? */
	if (sa_isset(&local_ip, SA_ADDR)) {
		sa_cpy(ip, &local_ip);
		return 0;
	}

	RSocketServ ss;
	RSocket s;
	TInt ret;

	ret = ss.Connect();
	if (KErrNone != ret) {
		DEBUG_WARNING("connecting to socket server fail (ret=%d)\n",
			      ret);
		return ECONNREFUSED;
	}

	ret = s.Open(ss, KAfInet, KSockDatagram, KProtocolInetUdp);
	if (KErrNone != ret) {
		DEBUG_WARNING("open socket failed (ret=%d)\n", ret);
		return ECONNREFUSED;
	}

	TInetAddr bind;
	bind.SetPort(0);
	bind.SetAddress(KInetAddrAny);

	ret = s.Bind(bind);
	if (KErrNone != ret) {
		DEBUG_WARNING("bind socket failed (ret=%d)\n", ret);
		return ECONNREFUSED;
	}

	TInetAddr local;
	s.LocalName(local);

	s.Close();
	ss.Close();

	sa_set_in(&local_ip, local.Address(), local.Port());

	DEBUG_NOTICE("local IP addr: %j\n", &local_ip);

	if (!sa_isset(&local_ip, SA_ADDR))
		return EINVAL;

	sa_cpy(ip, &local_ip);

	return 0;
}
int ILibSocketWrapper_socket(int socketType)
{
	int RetVal;

  // create a new connection for the socket
  RConnection* pConnection = new RConnection;

  // open a connection
  pConnection->Open(socketServer);

  TCommDbConnPref prefs;
  // set the preference for the requested interface
  prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);
  pConnection->Start(prefs);	

	if ( (socketType == SOCK_DGRAM) ||
       (socketType == SOCK_STREAM) )
	{
    RSocket *pSocket = new RSocket();

    if ( socketType == SOCK_DGRAM )
    {
      pSocket->Open(socketServer,
                    KAfInet,
                    KSockDatagram,
                    KProtocolInetUdp,
                    *pConnection);
    }
    else
    {
      pSocket->Open(socketServer,
                    KAfInet,
                    KSockStream,
                    KProtocolInetTcp,
                    *pConnection);
    }

    RetVal = ILibSocketWrapper_GetNextAvailableHandle();

    if( RetVal >= 0 )
    {
      SocketArray[RetVal] = (int)pSocket;
      ConnectionArray[RetVal] = pConnection;
    }
    else
    {
      pSocket->Close();
      delete pSocket;
      pConnection->Close();
      delete pConnection;
      RetVal = -1;
    }
  }

  return RetVal;
}
/*
 * Close a Socket from the array of type RSocket CArrayFixSeg<RSocket *>
 */
void CMultipleArray::CloseSocket(TInt aIndex)
	{
/* Close the socket
 * Remove entry from list
 */
	RSocket* sock = iSocketList->At(aIndex - 1);
	sock->Close();
	iSocketList->Delete(aIndex - 1);
	delete sock;
	}
enum TVerdict CSocketTest8_3::InternalDoTestStepL( void )
	{
	TVerdict verdict = EPass;
	
	Logger().WriteFormat(_L("Test Purpose: Ioctl auto bind and check started"));
	
	// 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);
	
	Logger().WriteFormat(_L("Opening a new socket"));
	RSocket socket;
	ret = socket.Open(ss, protoInfo.iAddrFamily, protoInfo.iSockType, protoInfo.iProtocol);
	Logger().WriteFormat(_L("Open returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Testing StartL() with Ioctl KDummyIoctlCheckStarted"));
	TRequestStatus stat;
	socket.Ioctl(KDummyIoctlCheckStarted, stat, NULL, KIoctlDummyLevel);
	User::WaitForRequest(stat);
	Logger().WriteFormat(_L("Ioctl returned with status %S"), &EpocErrorToText(stat.Int()));
	TESTL(KErrNone == stat.Int());
	
	Logger().WriteFormat(_L("Testing AutoBind()"));
	TSockAddr addr;
	Logger().WriteFormat(_L("Trying to Connect socket"));
	socket.Connect(addr, stat);
	User::WaitForRequest(stat);
	Logger().WriteFormat(_L("Connect returned with status %S"), &EpocErrorToText(stat.Int()));
	TESTL(KErrNone == stat.Int());
	
	Logger().WriteFormat(_L("Checking bound status with Ioctl"));
	socket.Ioctl(KDummyIoctlCheckBound, stat, NULL, KIoctlDummyLevel);
	User::WaitForRequest(stat);
	Logger().WriteFormat(_L("Ioctl returned with status %S"), &EpocErrorToText(stat.Int()));
	TESTL(KErrNone == stat.Int());
	
	CleanupStack::Pop(&ss);
	ss.Close();
	
	SetTestStepResult(verdict);
	return verdict;
	}
Exemple #27
0
int CTcpConn::Bind(TInetAddr &ia)
{
	TInt ret;

	ret = iSocket.SetOpt(KSoReuseAddr, KSolInetIp, 1);
	if (KErrNone != ret) {
		DEBUG_WARNING("SetOpt ReuseAddr: ret=%d\n", ret);
	}

	return kerr2errno(iSocket.Bind(ia));
}
void CJavaDebugAgentDriver::ClientDisconnected(CTcpServerHandler* aHandler)
{
    TInt handlerPos = iHandlers.Find(aHandler);
    if (handlerPos >= 0) {
        TInetAddr remote;
        RSocket* socket = aHandler->Socket();
        socket->LocalName(remote);

        // Delete a matching KeepAlive object. It doesn't matter which one.
        // Ideally we shouldn't create more than one KeepAlive per address
        // but we normally have no more than one client, so it's doesn't
        // really matter.
        for (TInt i = 0; i<iKeepAliveList.Count(); i++)
        {
            if (remote.Match(iKeepAliveList[i]->Address()))
            {
                delete iKeepAliveList[i];
                iKeepAliveList.Remove(i);
                break;
            }
        }

        // It's not obvious how we can recover from the situation when
        // we can't this handler to iDeadHandlers array. It's not safe
        // to delete the handler here because this callback is invoked 
        // by the handler, and it may access its this pointer after this
        // callback has returned. It that case, let's leave it in iHandlers
        // array. It screws things up but at least we don't leak memory.
        // Hopefully, this won't happen too often...
        if (iDeadHandlers.Append(aHandler) == KErrNone)
        {
            iHandlers.Remove(handlerPos);
            if (iHandlers.Count() == 0) {
                // It was our last client
                SetState(iServer ? EListening : EDisconnected);
            }
            // Schedule callback on a clean stack where we can safely
            // delete the handler
            iAsyncCleanup->CallBack();
        }
    }
    
    //Dima: Cleanup on start in InitL conflicts with installation
    //seemingly due to errors in Installer (ECOM framework panics
    //on loading midp2installerplugin.dll on installation after cleanup)
    //so we clean up on client disconnect.
    if (IsAutoCleanEnabled())
    {
        Log(_L("Cleaning up old data..."));
        iEngine->Cleanup();
        Log(_L("Done cleaning..."));
    }
}
TVerdict CSmsCapsSmsIoctlDeleteSms::doTestStepL()
	{

	RSocket socket;
	TRequestStatus status;
	TInt ret=socket.Open(iSocketServer,KSMSAddrFamily,KSockDatagram,KSMSDatagramProtocol);
	if(ret!=KErrNone)
		User::Leave(ret);
	CleanupClosePushL(socket);

	TSmsAddr smsaddr;
	smsaddr.SetSmsAddrFamily(ESmsAddrRecvAny);
	ret=socket.Bind(smsaddr);

	if(RProcess().HasCapability(ECapabilityWriteUserData, ECapabilityNetworkServices) && RProcess().HasCapability(ECapabilityReadUserData))
		{
		TESTL(ret != KErrPermissionDenied);
		}
	else
		{
		// skip this one
		CleanupStack::PopAndDestroy(&socket);
		return TestStepResult() ;
		}



	// Create message with SRR
	_LIT(KText,"This is a simple SMS!");
	CSmsMessage* msg=CreateSmsMessageL(KText,TSmsDataCodingScheme::ESmsAlphabet7Bit);
	CleanupStack::PushL(msg);

	RSmsSocketWriteStream writestream(socket);
	writestream << *msg;
	writestream.CommitL();
	CleanupStack::PopAndDestroy(msg);

	socket.Ioctl(KIoctlDeleteSmsMessage, status, NULL, KSolSmsProv);
	User::WaitForRequest(status);

	if(RProcess().HasCapability(ECapabilityWriteUserData))
		{
		TEST(status.Int() != KErrPermissionDenied);
		}
	else
		{
		TEST(status.Int() == KErrPermissionDenied);
		}

	CleanupStack::PopAndDestroy(&socket);

	return TestStepResult();
	}
int ILibSocketWrapper_listen(int socketObject,int backlog)
{
	RSocket *s = (RSocket*)SocketArray[socketObject];
	if(s->Listen(backlog)==KErrNone)
	{
		return(0);
	}
	else
	{
		return(-1);
	}
}