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);
	}
}
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);
}
// -----------------------------------------------------------------------------
// CLocalAddrResolver::GetLocalAddrL
// -----------------------------------------------------------------------------
//
void CLocalAddrResolver::GetLocalAddrL(TInetAddr& aAddr, TUint32 aIap)
	{
	RSocket socket;
	User::LeaveIfError( socket.Open( *iServer, KAfInet, KSockDatagram, 
		                             KProtocolInetUdp ) );

	if (socket.SetOpt( KSoInetEnumInterfaces, KSolInetIfCtrl ) == KErrNone )
		{
		TPckgBuf<TSoInetInterfaceInfo> opt;
		
		while ( socket.GetOpt( KSoInetNextInterface, KSolInetIfCtrl, opt ) == KErrNone)
			{
			TPckgBuf<TSoInetIfQuery> optifquery;
			optifquery().iName = opt().iName;
		
			if(socket.GetOpt( KSoInetIfQueryByName, KSolInetIfQuery, optifquery ) == KErrNone)
				{
				CheckAndSetAddr( aAddr, ( TInetAddr& )opt().iAddress,
				                 optifquery().iZone[1], aIap );
				}
			}
		}
		
	socket.Close();
	}
Example #4
0
// -----------------------------------------------------------------------------
// CMceLocalAddrResolver::RefreshLocalAddressesL
// -----------------------------------------------------------------------------
//
void CMceLocalAddrResolver::RefreshLocalAddressesL()
    {
    RSocket socket;
	User::LeaveIfError( socket.Open( iSocketServ, KAfInet, KSockDatagram, 
		                             KProtocolInetUdp ) );

	iAddr.Init( KAfInet );
	iIPv4Addr.Init( KAfInet );

	if ( socket.SetOpt( KSoInetEnumInterfaces, KSolInetIfCtrl ) == KErrNone )
		{
		TPckgBuf<TSoInetInterfaceInfo> info;
		while ( socket.GetOpt( KSoInetNextInterface,
		                       KSolInetIfCtrl, info ) == KErrNone )
			{
			TPckgBuf<TSoInetIfQuery> query;
			query().iName = info().iName;
			if ( socket.GetOpt( KSoInetIfQueryByName,
			                    KSolInetIfQuery, query ) == KErrNone )
				{
				if ( Match( info(), query() ) )
				    {
                    SetAddressesIfNotSet( info().iAddress );
				    }
				}
			}
		}
		
	socket.Close();
	}	
Example #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);
}
TVerdict CSmsCapsWapSetOption::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))
		{
		TESTL(ret != KErrPermissionDenied);
		}
	else
		{
		// skip this one
		CleanupStack::PopAndDestroy(&wapsock);
		return TestStepResult() ;
		}

	ret = wapsock.SetOpt(KWapSmsOptionNameDCS, KWapSmsOptionLevel, EWapSms8BitDCS);

	TEST(ret != KErrPermissionDenied);

	CleanupStack::PopAndDestroy(&wapsock);


	return	TestStepResult() ;
	}
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);
}
Example #8
0
// ---------------------------------------------------------------------------
// Sends UDP data.
// ---------------------------------------------------------------------------
//
TInt CSender::SendUdpData( const TInt aLocalPort,
                           const TInetAddr& aDestAddr,
                           const TDesC8& aUdpData,
                           const TUint aDscp )
    {
    RSocket* socket = NULL;
    iLocalPort = aLocalPort;
    iDestAddr = aDestAddr;
    
    if ( iLocalPort == 500 )
        {
        socket = &iSocket;
        }
    else if ( iLocalPort == 4500 )
        {
        socket = &iSocketNAT;
        }
    else 
        {        
        socket = &iSocketNokiaNAT;
        }
    
    TInt err = socket->SetOpt( KSoIpTOS, KSolInetIp, aDscp );
    
    if ( err == KErrNone )
        {
        err = socket->SetOpt( KSoUdpSynchronousSend, KSolInetUdp, 1 );
        }
    
    if ( err == KErrNone )
        {
        socket->SendTo( aUdpData, iDestAddr, 0, iStatus );    
        SetActive();
        }

#ifdef _DEBUG    
    TBuf<100> txt_addr;
    iDestAddr.Output( txt_addr );
    TUint32 port = iDestAddr.Port();
    DEBUG_LOG3( _L("Sending UDP data, local port=%d, dest address:port=%S:%d"),
            iLocalPort, &txt_addr, port );
    DEBUG_LOG2( _L(" DSCP=%d, err=%d"), aDscp, err );
#endif
    
    return err;
    }
enum TVerdict CSocketTest8_2::InternalDoTestStepL( void )
	{
	TVerdict verdict = EPass;
	
	Logger().WriteFormat(_L("Test Purpose: Ioctl observes InternalOptionBit"));
	
	// 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);
	
	// check internal options bit
	RSocket socket;
	Logger().WriteFormat(_L("Opening a new 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("Trying Ioctl on internal options bit"));
	TRequestStatus stat;
	socket.Ioctl(KInternalIoctlBit, stat);
	User::WaitForRequest(stat);
	Logger().WriteFormat(_L("Ioctl returned with status %S"), &EpocErrorToText(stat.Int()));
	TESTL(KErrAccessDenied == stat.Int());
	
	Logger().WriteFormat(_L("Trying to SetOpt internal options bit"));
	ret = socket.SetOpt(KSocketInternalOptionBit, KSOLSocket);
	Logger().WriteFormat(_L("SetOpt returned %S"), &EpocErrorToText(ret));
	TESTL(KErrAccessDenied == ret);
	
	Logger().WriteFormat(_L("Trying to GetOpt internal options bit"));
	TPckgBuf<TBool> boolean;
	ret = socket.GetOpt(KSocketInternalOptionBit, KSOLSocket, boolean);
	Logger().WriteFormat(_L("GetOpt returned %S"), &EpocErrorToText(ret));
	TESTL(KErrAccessDenied == ret);
	
	Logger().WriteFormat(_L("Testing StartL() with Ioctl KDummyIoctlCheckStarted"));
	socket.Ioctl(KDummyIoctlCheckStarted, 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;
	}
Example #10
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 CApConnectEngine::FetchIpAddressL()
{
	RSocket socket;
	CleanupClosePushL( socket);
	while (socket.Open(iSocketServ, KAfInet, KSockDatagram, KProtocolInetUdp,
			iConnect)!= KErrNone)
	{
	};
	TSoInetInterfaceInfo inf;
	TPckg<TSoInetInterfaceInfo> opt( inf);
	TRAPD(err, socket.SetOpt (KSoInetEnumInterfaces, KSolInetIfCtrl ))
	;
	if (err != KErrNone)
	{
		return;
	}

	while ( socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, opt)== KErrNone)
	{
		if ( inf.iAddress.Address()==0) // if the stored address is not an IPv4 address
		{
		}
		else
		{
			if ( inf.iAddress.IsUnspecified())
			{
				// Interface inf.iName has no address        	
			}
			else
			{
				// have to do this, strange
				TInetAddr addr;
				addr.SetAddress( inf.iAddress.Address());
				addr.Output(iConnInfo.ipAddress);
				// have to do this, strange

				if ( iConnInfo.ipAddress.Compare(KZeroIP)!= 0 && iConnInfo.ipAddress.Compare(KLocalIP)!= 0)
				{
					if ( iConnInfo.ipAddress.Left(3).Compare(_L("169"))!= 0)
					{
						CleanupStack::PopAndDestroy(); // socket
						return;
					}
				}
			}
		}
	}
	CleanupStack::PopAndDestroy(); // socket	
}
int ILibSocketWrapper_SetReuseAddr(int socketObject, int enabled)
{
	RSocket *s = (RSocket*)SocketArray[socketObject];
	return(s->SetOpt(KSoReuseAddr,KSolInetIp,enabled)==KErrNone?0:-1);
}
enum TVerdict CSocketTest8_6::InternalDoTestStepL( void )
	{
	TVerdict verdict = EPass;
	
	Logger().WriteFormat(_L("Test Purpose: Retention of socket options from before Accept to after Accept"));
	
	// connect to esock
	Logger().WriteFormat(_L("Attempting to connect to socket server"));
    RSocketServ ss1;
	TInt ret = OptimalConnect(ss1);
	TESTL(KErrNone == ret);
	CleanupClosePushL(ss1);
	
	Logger().WriteFormat(_L("Opening Socket on pdummy3"));
	RSocket sock1;
	ret = sock1.Open(ss1,_L("Dummy Protocol 3"));
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Binding Sock1"));
	TSockAddr addr;
	ret = sock1.Bind(addr);
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Listening on Sock1"));
	ret = sock1.Listen(5);
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Opening a null Socket"));
	RSocket nullSock;
	nullSock.Open(ss1);
	TESTL(KErrNone == ret);
	
	const TUint KBufferSize = 1024;
	Logger().WriteFormat(_L("Setting a whole bunch of KSOLSocket options on the parent (sock1) socket"));
	ret = sock1.SetOpt(KSOSendBuf, KSOLSocket, KBufferSize);
	TESTL(KErrNone == ret);
	ret = sock1.SetOpt(KSORecvBuf, KSOLSocket, KBufferSize);
	TESTL(KErrNone == ret);
	ret = sock1.SetOpt(KSODebug, KSOLSocket, ETrue);
	TESTL(KErrNone == ret);
	ret = sock1.SetOpt(KSONonBlockingIO, KSOLSocket);
	TESTL(KErrNone == ret);
	_LIT_SECURITY_POLICY_C2(KProcPolicy, ECapabilityNetworkServices, ECapabilityNetworkControl);
	ret = nullSock.SetOpt(KSOEnableTransfer, KSOLSocket, KProcPolicy().Package());
	TESTL(KErrNotReady == ret);
	
	Logger().WriteFormat(_L("Now simulating a remote connection to complete the accept"));
	ret = sock1.SetOpt(KDummyOptionSetConnectComplete, KIoctlDummyLevel);
	TESTL(KErrNone == ret);
	Logger().WriteFormat(_L("Now performing accept"));
	TRequestStatus stat;
	sock1.Accept(nullSock, stat);
	User::WaitForRequest(stat);
	TESTL(KErrNone == stat.Int());
	
	Logger().WriteFormat(_L("Now retrieving all the options set on the null socket with getOpts"));
	TInt retrievedOpt;
	ret = nullSock.GetOpt(KSOSendBuf, KSOLSocket, retrievedOpt);
	TESTL(KErrNone == ret);
	if (retrievedOpt != KBufferSize)
		{
		Logger().WriteFormat(_L("Opt KSOSendBuf did not return the correct value"));
		User::Leave(EFail);
		}	
	ret = nullSock.GetOpt(KSORecvBuf, KSOLSocket, retrievedOpt);
	TESTL(KErrNone == ret);
	if (retrievedOpt != KBufferSize)
		{
		Logger().WriteFormat(_L("Opt KSORecvBuf did not return the correct value"));
		User::Leave(EFail);
		}	
	ret = nullSock.GetOpt(KSODebug, KSOLSocket, retrievedOpt);
	TESTL(KErrNone == ret);
	if (!retrievedOpt) 
		{
		Logger().WriteFormat(_L("Opt KSODebug did not return the correct value"));
		User::Leave(EFail);
		}
	ret = nullSock.GetOpt(KSONonBlockingIO, KSOLSocket, retrievedOpt);
	TESTL(KErrNone == ret);
	if (!retrievedOpt)
		{
		Logger().WriteFormat(_L("Opt KSONonBlockingIO did not return the correct value"));
		User::Leave(EFail);
		}
	
	CleanupStack::Pop(&ss1);
	ss1.Close();
	
	return verdict;
	}
enum TVerdict CSocketTest8_4::InternalDoTestStepL( void )
	{
	TVerdict verdict = EPass;
	
	Logger().WriteFormat(_L("Test Purpose: Ioctl Get and Set Options"));
	
	// 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);
	
	// try SetLocalPort
	Logger().WriteFormat(_L("Opening a socket"));
	RSocket socket;
	ret = socket.Open(ss, _L("Dummy Protocol 1"));
	Logger().WriteFormat(_L("Open returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Trying SetLocalPort to 666"));
	ret = socket.SetLocalPort(666);
	Logger().WriteFormat(_L("SetLocalPort returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	Logger().WriteFormat(_L("Port now set to %d"), socket.LocalPort());
	TESTL(666 == socket.LocalPort());
	
	// try blocking Get/Set
	Logger().WriteFormat(_L("Testing blocking mode Get and Set options"));
	Logger().WriteFormat(_L("Trying to SetOption KSONonBlockingIO"));
	ret = socket.SetOpt(KSONonBlockingIO, KSOLSocket);
	Logger().WriteFormat(_L("SetOption returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Trying to GetOption KSONonBlockingIO"));
	TPckgBuf<TBool> boolean;
	ret = socket.GetOpt(KSONonBlockingIO, KSOLSocket, boolean);
	Logger().WriteFormat(_L("GetOption returned %S, value %d"), 
		&EpocErrorToText(ret), boolean());
	TESTL(KErrNone == ret);
	TESTL(TRUE == boolean());
	
	Logger().WriteFormat(_L("Trying to GetOption KSOBlockingIO"));
	ret = socket.GetOpt(KSOBlockingIO, KSOLSocket, boolean);
	Logger().WriteFormat(_L("GetOption returned %S, value %d"), 
		&EpocErrorToText(ret), boolean());
	TESTL(KErrNone == ret);
	TESTL(FALSE == boolean());
	
	Logger().WriteFormat(_L("Trying to SetOption KSOBlockingIO"));
	ret = socket.SetOpt(KSOBlockingIO, KSOLSocket);
	Logger().WriteFormat(_L("SetOption returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	
	Logger().WriteFormat(_L("Trying to GetOption KSONonBlockingIO"));
	ret = socket.GetOpt(KSONonBlockingIO, KSOLSocket, boolean);
	Logger().WriteFormat(_L("GetOption returned %S, value %d"), 
		&EpocErrorToText(ret), boolean());
	TESTL(KErrNone == ret);
	TESTL(FALSE == boolean());
	
	Logger().WriteFormat(_L("Trying to GetOption KSOBlockingIO"));
	ret = socket.GetOpt(KSOBlockingIO, KSOLSocket, boolean);
	Logger().WriteFormat(_L("GetOption returned %S, value %d"), 
		&EpocErrorToText(ret), boolean());
	TESTL(KErrNone == ret);
	TESTL(TRUE == boolean());
	
	CleanupStack::Pop(&ss);
	ss.Close();
	
	return verdict;
	}
Example #15
0
TInt Finger()
//
//
//
	{
	RTest test(_L("eSock Emulation test - Simple Finger Server"));

	test.Title();

	User::AfterInMicroSeconds(400000);
   
	// Connect to the actual socket server
	TRequestStatus stat;
	RSocketServ ss;
	TInt ret = ss.Connect();
	test(ret==KErrNone);

	test.Start(_L("Create Server Socket")); // {

	RSocket server;
	ret = server.Open(ss, KAFInet, KSockStream, KProtocolInetTCP);
	test(ret==KErrNone);

	test.Next(_L("Starting server"));
	TInetAddr svraddr(NULL_ADDR, TCP_PORT_FINGER);

	server.Bind(svraddr, stat);
	User::WaitForRequest(stat);
	test(stat==KErrNone);

	// Set client to non-blocking
	server.SetOpt(KSOBlockingIO,NULL,KSOLSocket);

	server.Listen(5, stat);
	User::WaitForRequest(stat);
	test(stat==KErrNone);


	FOREVER
		{
		const TInt KBufLen=256;
		RSocket client;
		TSockAddr cliaddr;

		test.Next(_L("Opening null socket to accept with"));

		ret=client.Open(ss);
		test(ret==KErrNone);

		test.Next(_L("Awaiting connection"));
		// Wait for connection request
		server.SetOpt(KSOBlockingIO,NULL,KSOLSocket);
		client.Accept(server, cliaddr, stat);		
		User::WaitForRequest(stat);
		test(stat==KErrNone);

		test.Next(_L("Get request string"));
		// Set client to non-blocking
		server.SetOpt(KSONonBlockingIO,NULL,KSOLSocket);

		// Read request string from remote client
		TBuf<KBufLen> reqbuf;
  		reqbuf.SetLength(KBufLen);

		test(RecvLine(test, reqbuf, client)>0);
		test.Printf(_L("Request: %s\n"), reqbuf.PtrZ());

		test.Next(_L("Send answer text"));
		TBuf<100> tmpbuf;
  		tmpbuf.SetLength(0);
		tmpbuf.Format(_L("No information available on user \"%s\".\r\n"), reqbuf.PtrZ());
		client.Write(tmpbuf,stat);
		User::WaitForRequest(stat);
		test(stat==KErrNone);
		tmpbuf.Format(_L("\r\n"), reqbuf.PtrZ());
		client.Write(tmpbuf,stat);
		User::WaitForRequest(stat);
		test(stat==KErrNone);

		test.Next(_L("Close"));
		test(client.Close()==KErrNone);
		// break;
		}

	test.Next(_L("Closing"));
	test(server.Close()==KErrNone);

	test.End(); // }

   	return 0;
    
    }
static QList<QNetworkInterfacePrivate *> interfaceListing()
{
    TInt err(KErrNone);
    QList<QNetworkInterfacePrivate *> interfaces;

    // Connect to Native socket server
    RSocketServ socketServ;
    err = socketServ.Connect();
    if (err)
        return interfaces;

    // Open dummy socket for interface queries
    RSocket socket;
    err = socket.Open(socketServ, _L("udp"));
    if (err) {
        socketServ.Close();
        return interfaces;
    }

    // Ask socket to start enumerating interfaces
    err =  socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);
    if (err) {
        socket.Close();
        socketServ.Close();
        return interfaces;
    }

    int ifindex = 0;
    TPckgBuf<TSoInetInterfaceInfo> infoPckg;
    TSoInetInterfaceInfo &info = infoPckg();
    while (socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, infoPckg) == KErrNone) {
        // Do not include IPv6 addresses because netmask and broadcast address cannot be determined correctly
        if (info.iName != KNullDesC && info.iAddress.IsV4Mapped()) {
            TName address;
            QNetworkAddressEntry entry;
            QNetworkInterfacePrivate *iface = 0;

            iface = new QNetworkInterfacePrivate;
            iface->index = ifindex++;
            interfaces << iface;
            iface->name = qt_TDesC2QString(info.iName);
            iface->flags = convertFlags(info);

            if (/*info.iFeatures&KIfHasHardwareAddr &&*/ info.iHwAddr.Family() != KAFUnspec) {
                for (TInt i = sizeof(SSockAddr); i < sizeof(SSockAddr) + info.iHwAddr.GetUserLen(); i++) {
                    address.AppendNumFixedWidth(info.iHwAddr[i], EHex, 2);
                    if ((i + 1) < sizeof(SSockAddr) + info.iHwAddr.GetUserLen())
                        address.Append(_L(":"));
                }
                address.UpperCase();
                iface->hardwareAddress = qt_TDesC2QString(address);
            }

            // Get the address of the interface
            info.iAddress.Output(address);
            entry.setIp(QHostAddress(qt_TDesC2QString(address)));

            // Get the interface netmask
            // For some reason netmask is always 0.0.0.0
            // info.iNetMask.Output(address);
            // entry.setNetmask( QHostAddress( qt_TDesC2QString( address ) ) );

            // Workaround: Let Symbian determine netmask based on IP address class
            // TODO: Works only for IPv4 - Task: 259128 Implement IPv6 support
            TInetAddr netmask;
            netmask.NetMask(info.iAddress);
            netmask.Output(address);
            entry.setNetmask(QHostAddress(qt_TDesC2QString(address)));

            // Get the interface broadcast address
            if (iface->flags & QNetworkInterface::CanBroadcast) {
                // For some reason broadcast address is always 0.0.0.0
                // info.iBrdAddr.Output(address);
                // entry.setBroadcast( QHostAddress( qt_TDesC2QString( address ) ) );

                // Workaround: Let Symbian determine broadcast address based on IP address
                // TODO: Works only for IPv4 - Task: 259128 Implement IPv6 support
                TInetAddr broadcast;
                broadcast.NetBroadcast(info.iAddress);
                broadcast.Output(address);
                entry.setBroadcast(QHostAddress(qt_TDesC2QString(address)));
            }

            // Add new entry to interface address entries
            iface->addressEntries << entry;

#if defined(QNETWORKINTERFACE_DEBUG)
            printf("\n       Found network interface %s, interface flags:\n\
                IsUp = %d, IsRunning = %d, CanBroadcast = %d,\n\
                IsLoopBack = %d, IsPointToPoint = %d, CanMulticast = %d, \n\
                ip = %s, netmask = %s, broadcast = %s,\n\
                hwaddress = %s",
                   iface->name.toLatin1().constData(),
                   iface->flags & QNetworkInterface::IsUp, iface->flags & QNetworkInterface::IsRunning, iface->flags & QNetworkInterface::CanBroadcast,
                   iface->flags & QNetworkInterface::IsLoopBack, iface->flags & QNetworkInterface::IsPointToPoint, iface->flags & QNetworkInterface::CanMulticast,
                   entry.ip().toString().toLatin1().constData(), entry.netmask().toString().toLatin1().constData(), entry.broadcast().toString().toLatin1().constData(),
                   iface->hardwareAddress.toLatin1().constData());
#endif
        }
    }
static pj_status_t rsock_enum_interface(int af,
					unsigned *p_cnt,
					pj_sockaddr ifs[]) 
{
    TInt rc;
    RSocket rSock;
    TPckgBuf<TSoInetInterfaceInfo> info;
    unsigned i;
    
    if (PjSymbianOS::Instance()->Connection()) {
    	
    	rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), 
    			af, PJ_SOCK_DGRAM, KProtocolInetUdp,
    			*PjSymbianOS::Instance()->Connection());
    } else {
    	
    	rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), 
    			af, PJ_SOCK_DGRAM, KProtocolInetUdp);
    			
    }
        
    if (rc != KErrNone)
	return PJ_RETURN_OS_ERROR(rc);
    
    rSock.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);
    
    for (i=0; i<*p_cnt &&
    		rSock.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, 
    		             info) == KErrNone; ) 
    {
    	TInetAddr &iAddress = info().iAddress;
    	int namelen;

#if TRACE_ME
		if (1) {
			pj_sockaddr a;
			char ipaddr[PJ_INET6_ADDRSTRLEN+2];
			
			namelen = sizeof(pj_sockaddr);
			if (PjSymbianOS::Addr2pj(iAddress, a, &namelen, 
									 PJ_FALSE) == PJ_SUCCESS) 
			{
				PJ_LOG(5,(THIS_FILE, "Enum: found address %s", 
						pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2)));
			}
		}
#endif
    	
    	namelen = sizeof(ifs[i]);
    	if (PjSymbianOS::Addr2pj(iAddress, ifs[i], &namelen, 
    							 PJ_TRUE) != PJ_SUCCESS)
    	{
    	    continue;
    	}

    	if (ifs[i].addr.sa_family != af)
		    continue;
    	
    	++i;
    }
    
    rSock.Close();
    
    // Done
    *p_cnt = i;
    
    return PJ_SUCCESS;
}
enum TVerdict CEsockTest29_10::easyTestStepL( void )
	{
	SetTestStepResult(EFail);
	TInt ret;
	const TUint KOneSecond = 1000000;
	
	Logger().WriteFormat(_L("Send/ Recv on PDummy3 socket but no avail MBuf Memory, mBuf becomes avail after send"));
	RSocketServ ss;
	ret = ss.Connect();
	TESTL(KErrNone == ret);	
    
    // open dummy prot 3
	Logger().WriteFormat(_L("Openning Dummy Protocol 3"));             
	RSocket sock;                                                  
	ret = sock.Open(ss,_L("Dummy Protocol 3"));
	TESTL(KErrNone == ret);
	
	// connect socket
	TSockAddr addr;
	TRequestStatus connStat;
	sock.Connect(addr, connStat);
	User::WaitForRequest(connStat);
	TESTL(KErrNone == connStat.Int());
	
	// send packet 1
	TRequestStatus stat;
	Logger().WriteFormat(_L("Attempting to create a packet to receive later"));	
	_LIT8(sendDataOne, "First Send");
	sock.Send(sendDataOne,0,stat);
	User::WaitForRequest(stat);
	TESTL(KErrNone == stat.Int());	
	// wait for packets to go through esock
	User::After(KOneSecond * 2);
	// gobble mBufs
	TInt nFree = 0;
	sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
	Logger().WriteFormat(_L("Attempting to set KDummyOptionSetGobbleMBufs Option in Protocol"));
	while (nFree > 0)
		{
		ret = sock.SetOpt(KDummyOptionSetGobbleMBufs, 0, 0);
		sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
		}
	Logger().WriteFormat(_L("Socket::SetOpt KDummyOptionSetGobbleMBufs returned %d"), ret);
	
	// we are running in high priority and allocating in a loop.
	// so kernel may not be able to enlarge the pools.
	// wait for kernel to enlarge the pool
	// We have to come out from the loop as well.
    User::After(KOneSecond * 2);
	
    sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
    Logger().WriteFormat(_L("Attempting to set KDummyOptionSetGobbleMBufs Option in Protocol"));
    while (nFree > 0)
        {
        ret = sock.SetOpt(KDummyOptionSetGobbleMBufs, 0, 0);
        sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
        }
    Logger().WriteFormat(_L("Socket::SetOpt KDummyOptionSetGobbleMBufs returned %d"), ret);
    // Once again
    User::After(KOneSecond * 2);
    sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
    Logger().WriteFormat(_L("Attempting to set KDummyOptionSetGobbleMBufs Option in Protocol"));
    while (nFree > 0)
        {
        ret = sock.SetOpt(KDummyOptionSetGobbleMBufs, 0, 0);
        sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
        }
    Logger().WriteFormat(_L("Socket::SetOpt KDummyOptionSetGobbleMBufs returned %d"), ret);
    // Once again
    User::After(KOneSecond * 2);
    sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
    Logger().WriteFormat(_L("Attempting to set KDummyOptionSetGobbleMBufs Option in Protocol"));
    while (nFree > 0)
        {
        ret = sock.SetOpt(KDummyOptionSetGobbleMBufs, 0, 0);
        sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
        }
    // Once again
    User::After(KOneSecond * 2);
    sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
    Logger().WriteFormat(_L("Attempting to set KDummyOptionSetGobbleMBufs Option in Protocol"));
    while (nFree > 0)
        {
        ret = sock.SetOpt(KDummyOptionSetGobbleMBufs, 0, 0);
        sock.GetOpt(KDummyOptionGetMBufFreeSpace, 0, nFree);
        }

	
	// send packet 2
	User::After(KOneSecond);
	TRequestStatus stat2;
	_LIT8(sendDataTwo, "Second Send");
	Logger().WriteFormat(_L("Sending Data - Should never complete"));             
	sock.Send(sendDataTwo,0,stat2);

	User::After(KOneSecond);
	Logger().WriteFormat(_L("Now cancel the Send"));     
	sock.CancelSend();
	User::WaitForRequest(stat2);
	TESTL(stat2 == KErrCancel);
	
	Logger().WriteFormat(_L("Receiving Data -- expected to pick up sendDataOne"));
	TBuf8<100> buf;          
	TRequestStatus stat3;
	sock.Recv(buf, 0, stat3);
	User::After(KOneSecond);
	User::WaitForRequest(stat3);
	TESTL(buf.Compare(sendDataOne) == 0);
		
	// send packet 3
	_LIT8(sendDataThree, "Third Send");
	Logger().WriteFormat(_L("Sending Data ... again"));             
	TRequestStatus stat4;
	sock.Send(sendDataThree,0,stat4);
	User::After(1000);
			
	// free memory
	Logger().WriteFormat(_L("Now free memory - should get send and receive completion"));	
	Logger().WriteFormat(_L("Attempting to set KDummyOptionSetFreeMBufs Option in Protocol"));	
	ret = sock.SetOpt(KDummyOptionSetFreeMBufs, 0, 0);
	Logger().WriteFormat(_L("Socket::SetOpt KDummyOptionSetFreeMBufs returned %d"), ret);
	TESTL(KErrNone == ret);	

	Logger().WriteFormat(_L("Sending Data - Should now complete"));             
	User::WaitForRequest(stat4);
	TESTL(stat4.Int() == KErrNone);

	// recieve data and compare contents to sent data
	Logger().WriteFormat(_L("Receiving Data"));
	sock.Recv(buf, 0, stat);
	User::WaitForRequest(stat);
	Logger().WriteFormat(_L("Recv has returned %d"), stat.Int());
	TBuf<100> buf16;
	buf16.Copy(buf);
	if(buf.Compare(sendDataThree) == 0)
		{
		SetTestStepResult(EPass);
		}
		
	Logger().WriteFormat(_L("Data Recv'ed is '%S'"), &buf16);
	sock.Close();
	ss.Close();
	return TestStepResult();
	}
enum TVerdict CEsockTest29_11::easyTestStepL( void )
	{
	TVerdict verdict = EFail;
	TInt ret;
	
	Logger().WriteFormat(_L("Send/ Recv on PDummy3 socket but no avail MBuf Memory, mBuf becomes avail after send"));
	RSocketServ ss;
	ret = ss.Connect();
	TESTL(KErrNone == ret);	
	CleanupClosePushL(ss);
    
    // open dummy prot 3
	Logger().WriteFormat(_L("Openning Dummy Protocol 3"));             
	RSocket sock;                                                  
	ret = sock.Open(ss,_L("Dummy Protocol 3"));
	TESTL(KErrNone == ret);
	
	// connecti socket
	TSockAddr addr;
	TRequestStatus stat;
	sock.Connect(addr, stat);
	User::WaitForRequest(stat);
	TESTL(KErrNone == stat.Int());	
	
	// drain MBuf Pool
	Logger().WriteFormat(_L("Attempting to set KDummyOptionSetGobbleMBufs Option in Protocol"));	
	ret = sock.SetOpt(KDummyOptionSetGobbleMBufs, 0, 0);
	Logger().WriteFormat(_L("Socket::SetOpt KDummyOptionSetFreeMBufs returned %d"), ret);
	
	// send data and wait for 1/10 seconds
	Logger().WriteFormat(_L("Sending Data"));     
	_LIT8( sendData, "bla bla bla bla");        
	sock.Send(sendData,0,stat);
	const TUint KTenMilliSecs = 10000; 
	User::After(KTenMilliSecs);
	
	// free all mbufs
	Logger().WriteFormat(_L("Attempting to set KDummyOptionSetFreeMBufs Option in Protocol"));	
	ret = sock.SetOpt(KDummyOptionSetFreeMBufs, 0, 0);
	TESTL(ret == KErrNone);
	Logger().WriteFormat(_L("Socket::SetOpt KDummyOptionSetFreeMBufs returned %d"), ret);

	// wait for send to return
	User::WaitForRequest(stat);
	Logger().WriteFormat(_L("Send has returned %d"), stat.Int());
	if(stat.Int() != KErrNone)
		{
		verdict = EFail;
		}
	
	// recieve data and verify that it is the same as send data
	TBuf8<20> recvBuf;
	TRequestStatus recvStatus;
	sock.Recv(recvBuf, 0, recvStatus);
	User::WaitForRequest(recvStatus);
	Logger().WriteFormat(_L("recieving data on PDummy3 has returned %d"), recvStatus.Int());
	if(recvStatus.Int() != KErrNone)
		{
		verdict = EFail;
		}
	Logger().WriteFormat(_L("Comparing Recieved data and Sent data"), recvStatus.Int());		
	if(recvBuf.Compare(sendData) == 0)
		{
		verdict = EPass; 
		}
	
	sock.Close();
	CleanupStack::PopAndDestroy(&ss);
    SetTestStepResult(verdict);
	return verdict;

	}
/*
 * Enumerates and returns all IPv4 interfaces
 */
static netif *enumIPvXInterfaces(JNIEnv *env, netif *ifs, TUint family)
{
    TPckgBuf<TSoInetInterfaceInfo> info;
    TSoInetInterfaceInfo &i = info();
    RSocket r;
    _LIT(proto, "ip");
    TInt err = r.Open(sserv, proto);
    if (err != KErrNone) {
	JNU_ThrowByName(env , JNU_JAVANETPKG "SocketException",
			 "Socket creation failed");
	return ifs;
    }

    /*
     * Iterate through each interface
     */
    int idx = 1;
    err = r.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl, 1);
    while ((err = r.GetOpt(KSoInetNextInterface,
	KSolInetIfCtrl, info)) == KErrNone)
    {
#ifdef _UNICODE
	TName n = i.iName;
	TUint8 n8[0x20];
	TPtr8 name8(n8, sizeof n8);
	TInt err = CnvUtfConverter::ConvertFromUnicodeToUtf8(name8, n);
	fprintf(stderr, "Interface proto %s status %x\n", name8.PtrZ(),
	    i.iState);
{
	TInt err = CnvUtfConverter::ConvertFromUnicodeToUtf8(name8, i.iTag);
	fprintf(stderr, "tag %s\n", name8.PtrZ());
}
	const char *if_name = (const char *)name8.PtrZ();
#else
	const char *if_name = (const char *)i.iTag.PtrZ();
#endif
	if (i.iState == EIfUp) {
	    TInetAddr ia = i.iAddress;
	    fprintf(stderr, "Address %x\n", ia.Address());
	}
	if (i.iAddress.Family() == family) {
	    TInetAddr ia = i.iAddress;
	    /*
	     * Add to the list 
	     */
	    ifs = addif(env, ifs, if_name, idx, KAfInet, ia);

	    /*
	     * If an exception occurred then free the list
	     */
	    if ((*env)->ExceptionOccurred(env)) {
		freeif(ifs);
		ifs = NULL;
		goto done;
	    }
	}
	++idx;
    }

{
    TPckgBuf<TSoInetIfQuery> q1;
    TSoInetIfQuery &q = q1();
    TInt inum = 1;
    q.iIndex = inum;

    while ((err = r.GetOpt(KSoInetIfQueryByIndex,
	KSolInetIfQuery, q1)) == KErrNone)
    {
	fprintf(stderr, "Interface %d up %d\n", inum, q.iIsUp);
#ifdef _UNICODE
	TUint8 n8[0x20];
	TPtr8 name8(n8, sizeof n8);
	TInt err = CnvUtfConverter::ConvertFromUnicodeToUtf8(name8, q.iName);
	fprintf(stderr, "Interface %d name %s\n", inum, name8.PtrZ());
#endif
	fprintf(stderr, "src addr %x\n", q.iSrcAddr.Address());
	fprintf(stderr, "dst addr %x\n", q.iDstAddr.Address());
	q.iIndex = ++inum;
    }
}

done:
    r.Close();
    return ifs;
}
static QList<QNetworkInterfacePrivate *> interfaceListing()
{
    TInt err(KErrNone);
    QList<QNetworkInterfacePrivate *> interfaces;
    QList<QHostAddress> addressesWithEstimatedNetmasks;

    // Open dummy socket for interface queries
    RSocket socket;
    err = socket.Open(qt_symbianGetSocketServer(), _L("udp"));
    if (err) {
        return interfaces;
    }

    // Ask socket to start enumerating interfaces
    err =  socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);
    if (err) {
        socket.Close();
        return interfaces;
    }

    int ifindex = 0;
    TPckgBuf<TSoInetInterfaceInfo> infoPckg;
    TSoInetInterfaceInfo &info = infoPckg();
    while (socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, infoPckg) == KErrNone) {
        if (info.iName != KNullDesC) {
            TName address;
            QNetworkAddressEntry entry;
            QNetworkInterfacePrivate *iface = 0;

            iface = new QNetworkInterfacePrivate;
            iface->index = ifindex++;
            interfaces << iface;
            iface->name = qt_TDesC2QString(info.iName);
            iface->flags = convertFlags(info);

            if (/*info.iFeatures&KIfHasHardwareAddr &&*/ info.iHwAddr.Family() != KAFUnspec) {
                for (TInt i = sizeof(SSockAddr); i < sizeof(SSockAddr) + info.iHwAddr.GetUserLen(); i++) {
                    address.AppendNumFixedWidth(info.iHwAddr[i], EHex, 2);
                    if ((i + 1) < sizeof(SSockAddr) + info.iHwAddr.GetUserLen())
                        address.Append(_L(":"));
                }
                address.UpperCase();
                iface->hardwareAddress = qt_TDesC2QString(address);
            }

            // Get the address of the interface
            entry.setIp(qt_QHostAddressFromTInetAddr(info.iAddress));

#if defined(QNETWORKINTERFACE_DEBUG)
            qDebug() << "address is" << info.iAddress.Family() << entry.ip();
            qDebug() << "netmask is" << info.iNetMask.Family() << qt_QHostAddressFromTInetAddr( info.iNetMask );
#endif

            // Get the interface netmask
            if (info.iNetMask.IsUnspecified()) {
                // For some reason netmask is always 0.0.0.0 for IPv4 interfaces
                // and loopback interfaces (which we statically know)
                if (info.iAddress.IsV4Mapped()) {
                    if (info.iFeatures & KIfIsLoopback) {
                        entry.setPrefixLength(32);
                    } else {
                        // Workaround: Let Symbian determine netmask based on IP address class (IPv4 only API)
                        TInetAddr netmask;
                        netmask.NetMask(info.iAddress);
                        entry.setNetmask(QHostAddress(netmask.Address())); //binary convert v4 address
                        addressesWithEstimatedNetmasks << entry.ip();
#if defined(QNETWORKINTERFACE_DEBUG)
                        qDebug() << "address class determined netmask" << entry.netmask();
#endif
                    }
                } else {
                    // For IPv6 interfaces
                    if (info.iFeatures & KIfIsLoopback) {
                        entry.setPrefixLength(128);
                    } else if (info.iNetMask.IsUnspecified()) {
                        //Don't see this error for IPv6, but try to handle it if it happens
                        entry.setPrefixLength(64); //most common
#if defined(QNETWORKINTERFACE_DEBUG)
                        qDebug() << "total guess netmask" << entry.netmask();
#endif
                        addressesWithEstimatedNetmasks << entry.ip();
                    }
                }
            } else {
                //Expected code path for IPv6 non loopback interfaces (IPv4 could come here if symbian is fixed)
                entry.setNetmask(qt_QHostAddressFromTInetAddr(info.iNetMask));
#if defined(QNETWORKINTERFACE_DEBUG)
                qDebug() << "reported netmask" << entry.netmask();
#endif
            }

            // broadcast address is determined from the netmask in postProcess()

            // Add new entry to interface address entries
            iface->addressEntries << entry;

#if defined(QNETWORKINTERFACE_DEBUG)
            qDebug("\n       Found network interface %s, interface flags:\n\
                IsUp = %d, IsRunning = %d, CanBroadcast = %d,\n\
                IsLoopBack = %d, IsPointToPoint = %d, CanMulticast = %d, \n\
                ip = %s, netmask = %s, broadcast = %s,\n\
                hwaddress = %s",
                   iface->name.toLatin1().constData(),
                   iface->flags & QNetworkInterface::IsUp, iface->flags & QNetworkInterface::IsRunning, iface->flags & QNetworkInterface::CanBroadcast,
                   iface->flags & QNetworkInterface::IsLoopBack, iface->flags & QNetworkInterface::IsPointToPoint, iface->flags & QNetworkInterface::CanMulticast,
                   entry.ip().toString().toLatin1().constData(), entry.netmask().toString().toLatin1().constData(), entry.broadcast().toString().toLatin1().constData(),
                   iface->hardwareAddress.toLatin1().constData());
#endif
        }
    }
Example #22
0
SilcStream silc_net_udp_connect(const char *local_ip_addr, int local_port,
				const char *remote_ip_addr, int remote_port,
				SilcSchedule schedule)
{
  SilcSymbianSocket *s;
  SilcStream stream;
  TInetAddr local, remote;
  TRequestStatus status;
  RSocket *sock = NULL;
  RSocketServ *ss = NULL;
  TInt ret;

  SILC_LOG_DEBUG(("Creating UDP stream"));

  if (!schedule) {
    schedule = silc_schedule_get_global();
    if (!schedule) {
      silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
      goto err;
    }
  }

  SILC_LOG_DEBUG(("Binding to local address %s",
		  local_ip_addr ? local_ip_addr : "0.0.0.0"));

  sock = new RSocket;
  if (!sock)
    goto err;

  ss = new RSocketServ;
  if (!ss)
    goto err;

  /* Open socket server */
  ret = ss->Connect();
  if (ret != KErrNone)
    goto err;

#ifdef SILC_THREADS
  /* Make our socket shareable between threads */
  ss->ShareAuto();
#endif /* SILC_THREADS */

  /* Get local bind address */
  if (!silc_net_set_sockaddr(&local, local_ip_addr, local_port))
    goto err;

  /* Create the socket */
  ret = sock->Open(*ss, KAfInet, KSockDatagram, KProtocolInetUdp);
  if (ret != KErrNone) {
    SILC_LOG_ERROR(("Cannot create socket"));
    goto err;
  }

  /* Set the socket options */
  sock->SetOpt(KSoReuseAddr, KSolInetIp, 1);

  /* Bind the listener socket */
  ret = sock->Bind(local);
  if (ret != KErrNone) {
    SILC_LOG_DEBUG(("Cannot bind socket"));
    goto err;
  }

  /* Set to connected state if remote address is provided. */
  if (remote_ip_addr && remote_port) {
    if (silc_net_set_sockaddr(&remote, remote_ip_addr, remote_port)) {
      sock->Connect(remote, status);
      if (status != KErrNone) {
	SILC_LOG_DEBUG(("Cannot connect UDP stream"));
	goto err;
      }
    }
  }

  /* Encapsulate into socket stream */
  s = silc_create_symbian_socket(sock, ss);
  if (!s)
    goto err;
  stream =
    silc_socket_udp_stream_create((SilcSocket)s, local_ip_addr ?
				  silc_net_is_ip6(local_ip_addr) : FALSE,
				  remote_ip_addr ? TRUE : FALSE, schedule);
  if (!stream)
    goto err;

  SILC_LOG_DEBUG(("UDP stream created, fd=%d", sock));
  return stream;

 err:
  if (sock)
    delete sock;
  if (ss) {
    ss->Close();
    delete ss;
  }
  return NULL;
}
/**
 * Change the default MTU size on NCM networking connection
 */
void CNcmConnectionManager::SetCustomMtuL()
    {    
    OstTraceFunctionEntry0(CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_ENTRY);
    
    RSocket socket;
    User::LeaveIfError(socket.Open(iSocketServ, KAfInet, KSockStream, KProtocolInetTcp,
            iConnection));

    TPckgBuf<TSoInet6InterfaceInfo> interfaceInfo;
    TPckgBuf<TConnInterfaceName> interfaceName;
    
    TUint cnt = 0;
    iConnection.EnumerateConnections(cnt); // Count all underlying interfaces
    
    TUint iap = iConnPref.IapId();
    TInt index = 1;
    for (index = 1; index <= cnt; index++)
        {
        TConnectionInfoBuf info;
        iConnection.GetConnectionInfo(index, info);
        if (info().iIapId == iap)
            {
            break;
            }
        }
    
    if (index > cnt)
        {
        OstTrace0( TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL, "Can not find an interface based on NCM!" );
        User::Leave(KErrNotFound);
        }
    
    interfaceName().iIndex = index;    
    OstTraceExt2( TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_INTER_INFO, ";cnt=%d;interfaceName().iIndex=%u", cnt, interfaceName().iIndex );
    User::LeaveIfError(iConnection.Control(KCOLProvider, KConnGetInterfaceName, interfaceName));
    OstTraceExt3( TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_NEW_MTU_SIZE, ";Interface Name=%S, ;current MTU=%d. MTU size will be changed to %d!", interfaceName().iName, interfaceInfo().iMtu, KEthernetFrameSize);
        
    TInt err = socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);
    if (err != KErrNone)
        {
        OstTrace1(TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_START_INTER_ENUM, "Failed to set KSoInetEnumInterfaces option [%d]", err);
        User::LeaveIfError(err);              
        }
        
    err = KErrNotFound;
    while (socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, interfaceInfo) == KErrNone)
        {
        OstTraceExt1(TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_INTER_NAME, "InterfaceInfo().iName = %S", interfaceInfo().iName);
        OstTrace1(TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_INTER_MTU, "InterfaceInfo().iMtu = %d", interfaceInfo().iMtu);
        if (interfaceInfo().iName == interfaceName().iName)
            {
            // found the interface
            err = KErrNone;
            break;
            }
        }
    if (KErrNone != err)
        {
        OstTrace1(TRACE_ERROR, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_SEARCH_FAIL, "Can not find NCM connection: err=%x", err);
        User::LeaveIfError(err);
        }
    
    // Set new MTU size
    TPckgBuf<TSoInet6InterfaceInfo> newinterfaceInfo;
    newinterfaceInfo().iMtu = KEthernetFrameSize;	
    newinterfaceInfo().iDoPrefix = 0;
    newinterfaceInfo().iDoId = 0;
    newinterfaceInfo().iDoState = 0;
    newinterfaceInfo().iDoAnycast = 0;
    newinterfaceInfo().iDoProxy = 0;
    newinterfaceInfo().iAlias = interfaceInfo().iAlias;
    newinterfaceInfo().iDelete = interfaceInfo().iDelete;
    newinterfaceInfo().iState = interfaceInfo().iState;
    newinterfaceInfo().iSpeedMetric = interfaceInfo().iSpeedMetric;
    newinterfaceInfo().iFeatures = interfaceInfo().iFeatures;
    newinterfaceInfo().iTag = interfaceInfo().iTag;
    newinterfaceInfo().iName = interfaceInfo().iName;
    newinterfaceInfo().iSpeedMetric = interfaceInfo().iSpeedMetric;
    newinterfaceInfo().iFeatures = interfaceInfo().iFeatures;	
    newinterfaceInfo().iHwAddr = interfaceInfo().iHwAddr;
    newinterfaceInfo().iAddress = interfaceInfo().iAddress;
    newinterfaceInfo().iNetMask = interfaceInfo().iNetMask;
    newinterfaceInfo().iDefGate = interfaceInfo().iDefGate;
    newinterfaceInfo().iNameSer2 = interfaceInfo().iNameSer2;
    newinterfaceInfo().iNameSer1 = interfaceInfo().iNameSer1;
	
    OstTrace0( TRACE_NORMAL, CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_PRE_SETMTU, "About to change the default MTU size." );
	User::LeaveIfError(socket.SetOpt(KSoInetConfigInterface, KSolInetIfCtrl, newinterfaceInfo));

    socket.Close();
    
    OstTraceFunctionExit0(CNCMCONNECTIONMANAGER_SETCUSTOMMTUL_EXIT);
    }
enum TVerdict CTestStepNullAgtLoopbackTest::doTestStepL(void)
{
    __UHEAP_MARK;

    TInt r;                // the result of various operations
    TRequestStatus status; // status of asynchronous ops

    RSocketServ server;    // connection paraphanelia
    RConnection connection;
    RSocket socket;

    TInetAddr dest;
    dest.SetAddress(KDummyNifLocalAddressBase + 4);
    dest.SetPort(KPortNo);

    TBuf8<KBufferLength> buffer;

    // connect to the socket server
    r = server.Connect();
    TESTEL(r == KErrNone, r);
    CleanupClosePushL(server);

    // this is why we needed a socket server...
    r = connection.Open(server, KAfInet);
    TESTEL(r == KErrNone, r);
    CleanupClosePushL(connection);

    // start the connection up (outgoing)
    connection.Start(status);
    User::WaitForRequest(status);
    TESTEL(status.Int() == KErrNone, status.Int());

    // open a udp socket
    r = socket.Open(server, KAfInet, KSockDatagram, KProtocolInetUdp);
    TESTEL(r == KErrNone, r);
    CleanupClosePushL(socket);
    TESTL(socket.SetOpt(KSoReuseAddr, KSolInetIp, 1)==KErrNone);
    // set the source port number - otherwise will panic cos it's zero
    r = socket.SetLocalPort(KPortNo);
    TESTEL(r == KErrNone, r);

    // build some data to send on the socket
    // this is an ICMP ping request apparently
    buffer.SetMax();
    buffer.FillZ();
    buffer[0] = (TUint8) 0x8;		// ICMP type = 8
    buffer[1] = (TUint8) 0x0;		// ICMP code = 0
    buffer[2] = (TUint8) 0xF7;		// ICMP checksum high byte
    buffer[3] = (TUint8) 0xFF;		// ICMP checksum low byte
    // NB the rest of the buffer is zero
    // hence the checksum (0xFFFF - 0x800) since 0x8
    // is the only non-zero element of the buffer

    // send the data out over the socket
    socket.SendTo(buffer, dest, 0, status);
    User::WaitForRequest(status);
    TESTEL(status.Int() == KErrNone, status.Int());

    buffer.Zero();
    // I expect to get the data looped back from the dummy NIF
    socket.RecvFrom(buffer, dest, 0, status);
    User::WaitForRequest(status);
    TESTEL(status.Int() == KErrNone, status.Int());

    // check that what we sent is what we got back
    if (status.Int() == KErrNone)
    {
        // if the receive times out and we access buffer we get a panic
        TEST(buffer[0] == 0x08);
        TEST(buffer[1] == 0x00);
        TEST(buffer[2] == 0xF7);
        TEST(buffer[3] == 0xFF);
    }

    // close the socket
    socket.Shutdown(RSocket::ENormal, status);
    User::WaitForRequest(status);
    TESTEL(status.Int() == KErrNone, status.Int());
    CleanupStack::Pop();

    // force the destruction of the connection
    r = connection.Stop();
    TESTEL(r == KErrNone, r);
    CleanupStack::Pop();

    // close the socket server
    server.Close();
    CleanupStack::Pop();

    __UHEAP_MARKEND;

    return iTestStepResult;
}