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); }
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); }
// ----------------------------------------------------------------------------- // 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(); }
// ----------------------------------------------------------------------------- // 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(); }
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(); }
SYSCALL(int, maConnGetAddr(MAHandle conn, MAConnAddr* addr)) { LOGST("maConnGetAddr(%i, 0x%08X)", conn, addr); if(conn == HANDLE_LOCAL) { if(addr->family == CONN_FAMILY_BT) { TBTDevAddr btaddr; //TPckgBuf<TBTDevAddr> pckg(btaddr); //old style, might work on Symbian 7.0 and earlier //update: doesn't work on 6630. #if 0//!defined(__SERIES60_3X__) RSocket socket; socket.Open(gSocketServ, KBTAddrFamily, KSockSeqPacket, KL2CAP); TRequestStatus status; socket.Ioctl(KHCILocalAddressIoctl, status, &pckg, KSolBtHCI); User::WaitForRequest(status); LOG("KHCILocalAddressIoctl result: %i\n", status.Int()); socket.Close(); if(status != KErrNone) { return CONNERR_GENERIC; } #else #if 0 //doesn't work; bug in Symbian. int result = RProperty::Get(KUidSystemCategory, KPropertyKeyBluetoothGetLocalDeviceAddress, pckg); LOG("KPropertyKeyBluetoothGetLocalDeviceAddress result: %i\n", result); if(result != KErrNone) { return CONNERR_GENERIC; } #else //open a server socket and read its address. RSocket socket; socket.Open(gSocketServ, KBTAddrFamily, KSockStream, KRFCOMM); int channel; LHEL_BASE(socket.GetOpt(KRFCOMMGetAvailableServerChannel, KSolBtRFCOMM, channel), return CONNERR_GENERIC); TBTSockAddr btsockaddr; btsockaddr.SetPort(channel); LHEL_BASE(socket.Bind(btsockaddr), return CONNERR_GENERIC); socket.LocalName(btsockaddr); socket.Close(); btaddr = btsockaddr.BTAddr(); #endif //0 #endif //0//__SERIES60_3X__ storeBtAddr(btaddr, addr); return 1; } else { //TCP server return CONNERR_INTERNAL;
static int connect_test() { RSocketServ rSockServ; RSocket rSock; TInetAddr inetAddr; TRequestStatus reqStatus; char buffer[16]; TPtrC8 data((const TUint8*)buffer, (TInt)sizeof(buffer)); int rc; rc = rSockServ.Connect(); if (rc != KErrNone) return rc; rc = rSock.Open(rSockServ, KAfInet, KSockDatagram, KProtocolInetUdp); if (rc != KErrNone) { rSockServ.Close(); return rc; } inetAddr.Init(KAfInet); inetAddr.Input(_L("127.0.0.1")); inetAddr.SetPort(80); rSock.Connect(inetAddr, reqStatus); User::WaitForRequest(reqStatus); if (reqStatus != KErrNone) { rSock.Close(); rSockServ.Close(); return rc; } rSock.Send(data, 0, reqStatus); User::WaitForRequest(reqStatus); if (reqStatus!=KErrNone) { rSock.Close(); rSockServ.Close(); return rc; } rSock.Close(); rSockServ.Close(); return KErrNone; }
/** * 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; }
// --------------------------------------------------------------------------- // Cleans partial created channel data based on TATExtCleanupInfo // --------------------------------------------------------------------------- // void CDunBtPlugin::CleanPartialChanneldata( TBtCleanupInfo& aCleanupInfo ) { FTRACE(FPrint(_L("CDunBtPlugin::CleanPartialChanneldata()"))); RSocket* socket = &iBTPorts[aCleanupInfo.iEntityIndex].iBTPort; iTransporter->FreeChannel( socket ); iBTPorts[aCleanupInfo.iEntityIndex].iChannelNum = KErrNotFound; socket->Close(); if ( aCleanupInfo.iNewEntity ) { iBTPorts.Remove( aCleanupInfo.iEntityIndex ); } FTRACE(FPrint(_L("CDunBtPlugin::CleanPartialChanneldata() complete"))); }
// Gets the local device class. // Arguments: // - aDeviceData - object to hold the retrieved class data. // // Returns an error code. //static TInt GetLocalDeviceClass(TDeviceData& aDeviceData) static TInt GetLocalDeviceClass(TBTDeviceClass& aDeviceClass) { TInt err = KErrNone; #if defined(__SYMBIAN_9__) TInt cod; err = RProperty::Get(KPropertyUidBluetoothCategory, KPropertyKeyBluetoothGetDeviceClass, cod); if (err == KErrNone) { aDeviceClass = TBTDeviceClass(cod); } #elif defined(__SYMBIAN_8__) TInt cod; err = RProperty::Get(KPropertyUidBluetoothCategory, KPropertyKeyBluetoothDeviceClass, cod); if (err == KErrNone) { aDeviceClass = TBTDeviceClass(cod); } #else RSocketServ socketServ; RSocket sock; err = socketServ.Connect(); if (!err) { err = sock.Open(socketServ, KBTAddrFamily, KSockSeqPacket, KL2CAP); if (!err) { THCIDeviceClassBuf codBuf; TRequestStatus status; sock.Ioctl(KHCIReadDeviceClassIoctl, status, &codBuf, KSolBtHCI); User::WaitForRequest(status); if (status.Int() == KErrNone) { aDeviceClass = TBTDeviceClass(codBuf().iMajorServiceClass, codBuf().iMajorDeviceClass, codBuf().iMinorDeviceClass); } sock.Close(); } socketServ.Close(); } #endif return err; }
// from PDIS miso library // Gets the local device address. // Arguments: // - aAddress - object to hold the retrieved address. // // Returns an error code. static TInt GetLocalAddress(TBTDevAddr& aAddress) { TInt err = KErrNone; #if defined(__SYMBIAN_9__) TPtr8 ptr(aAddress.Des()); err = RProperty::Get(KPropertyUidBluetoothCategory, KPropertyKeyBluetoothGetLocalDeviceAddress, ptr); #elif defined(__SYMBIAN_8__) TPtr8 ptr(aAddress.Des()); err = RProperty::Get(KPropertyUidBluetoothCategory, KPropertyKeyBluetoothLocalDeviceAddress, ptr); #else RSocketServ socketServ; err = socketServ.Connect(); if (err) return err; // this solution comes from the "bthci" Series 60 example; // does not work on Symbian 8-up RSocket socket; err = socket.Open(socketServ, KBTAddrFamily, KSockSeqPacket, KL2CAP); if (!err) { TPckgBuf<TBTDevAddr> btDevAddrPckg; TRequestStatus status; socket.Ioctl(KHCILocalAddressIoctl, status, &btDevAddrPckg, KSolBtHCI); User::WaitForRequest(status); err = status.Int(); if (!err) { TPtrC8 src(btDevAddrPckg().Des()); TPtr8 dest(aAddress.Des()); dest.Copy(src); } socket.Close(); } socketServ.Close(); #endif return err; }
void CTe_rtpSuite::ConfigureReflectorModeL(TBool aMode, TInetAddr& aAddr) { /* Configures the reflector to change the SSRC or not */ RSocketServ sockServer; //Open a connection RConnection conn; User::LeaveIfError(sockServer.Connect()); CleanupClosePushL(sockServer); User::LeaveIfError(conn.Open(sockServer)); CleanupClosePushL(conn); //Start the connection User::LeaveIfError(conn.Start()); RSocket ctrlSock; User::LeaveIfError(ctrlSock.Open(sockServer,KAfInet, KSockDatagram, KProtocolInetUdp, conn)); CleanupClosePushL(ctrlSock); TBuf8<64> lCmdBuff; TUint8* lPtr = const_cast<TUint8*>(lCmdBuff.Ptr()); TUint32* lIntData = (TUint32*)lPtr; *lIntData = ByteOrder::Swap32(0xFF00BABE); if (aMode) { *(lIntData + 1) = ByteOrder::Swap32(0xCD000100); } else { *(lIntData + 1) = ByteOrder::Swap32(0xCD000101); } lCmdBuff.SetLength(64); TRequestStatus lMyReqStat; ctrlSock.SendTo(lCmdBuff,aAddr,0,lMyReqStat); User::WaitForRequest(lMyReqStat); ctrlSock.Close(); conn.Close(); sockServer.Close(); CleanupStack::Pop(3); }
TVerdict CRtpNegTestsFailNoBearer::doTestStepL() /** * @return - TVerdict code */ { SetTestStepResult(EFail); TInt err; TRequestStatus stat; if(KErrNone == InitDummySubConL(CSubConRTPGenericParamSetDummy::KFailNoBearer)) { /* try to Open one more Socket on Subconnection. This should fail */ RSocket sock; err = sock.Open(iSocketServ, KAfInet, KSockDatagram, KProtocolInetUdp, iSubCon); if(KErrNone != err) { SetTestStepResult(EPass); } sock.Close(); } return TestStepResult(); }
int ILibSocketWrapper_close(int socketObject) { // lookup the socket handle and close and delete if exists RSocket *s = (RSocket*)SocketArray[socketObject]; if ( s != NULL ) { s->Close(); delete s; SocketArray[socketObject] = 0; } // lookup the connection handle and close and delete if exists RConnection *c = ConnectionArray[socketObject]; if ( c != NULL ) { c->Close(); delete c; ConnectionArray[socketObject] = NULL; } return(0); }
void CListener::ArpRegisterL() { /* Open a connectionless socket to a known tcp/ip adapter and send it an ICMP msg (ping request). This has the effect of registring the Listener to the ARP, so that it's address can be resolvd. We are not interested in the echo (response to ping). */ RSocket tempSocket; User::LeaveIfError(tempSocket.Open(iSockServ, KAfInet,KSockDatagram, KProtocolInetIcmp)); TRequestStatus stat; // Create the data to send (Ping msg) HPingHeader* sendData; sendData = HPingHeader::NewL(KDefaultPingSize); TInt Id; Id=User::TickCount()&KMaxTUint16; TUint nrTransmitted(0); sendData->FormatSend(Id, nrTransmitted++); TInetAddr knownAddr = iOptions->KnownAdapterAddr(); tempSocket.SendTo(*(sendData->Grab()), knownAddr, 0, stat); User::WaitForRequest(stat); if(stat == KErrNone) { LOGLINE2(_L("ArpRegisterL() status: %d"), stat.Int()); } else { LOGLINE2(_L("WARNING ArpRegisterL() failure!! status: %d"), stat.Int()); } delete sendData; tempSocket.Close(); }
enum TVerdict CSocketTest8_1::InternalDoTestStepL( void ) { TVerdict verdict = EPass; Logger().WriteFormat(_L("Test Purpose: Ioctl returns not started on null socket")); // 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); //PG 14/02/2001 //Added test for defect: TOD-4QLDXY - Ioctl on incorrectly opened socket crashes socket server. Logger().WriteFormat(_L("Opening a socket with no protocol")); RSocket socketNoProtoDefined; ret = socketNoProtoDefined.Open(ss); Logger().WriteFormat(_L("Open returned %S"), &EpocErrorToText(ret)); TESTL(KErrNone == ret); // see if it's started Logger().WriteFormat(_L("Check Ioctl fails")); TRequestStatus stat; socketNoProtoDefined.Ioctl(KDummyIoctlCheckStarted, stat); User::WaitForRequest(stat); Logger().WriteFormat(_L("Ioctl returned with status %S"), &EpocErrorToText(stat.Int())); TESTL(KErrNotSupported == stat.Int()); socketNoProtoDefined.Close(); CleanupStack::Pop(&ss); ss.Close(); SetTestStepResult(verdict); return verdict; }
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; }
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; }
/* * 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; // 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; }
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 } }
enum TVerdict CSocketTest7_1::InternalDoTestStepL( void ) { TVerdict verdict = EPass; Logger().WriteFormat(_L("Test Purpose: Alloc Heaven during socket open")); #if defined (_DEBUG_SOCKET_FUNCTIONS) // connect to esock Logger().WriteFormat(_L("Attempting to connect to socket server")); RSocketServ ss; TInt ret = OptimalConnect(ss); CleanupClosePushL(ss); Logger().WriteFormat(_L("Connect returned %S"), &EpocErrorToText(ret)); TESTL(KErrNone == ret); // get a protocol Logger().WriteFormat(_L("Attempting to FindProtocol dummy protocol 1")); TProtocolDesc protoInfo; ret = ss.FindProtocol(_L("Dummy Protocol 1"), protoInfo); Logger().WriteFormat(_L("FindProtocol returned %S"), &EpocErrorToText(ret)); TESTL(KErrNone == ret); // Stretch socket arrays in the server. RSocket *sockets = new (ELeave) RSocket[KNumStretchOpens]; CleanupArrayDeletePushL(sockets); TInt i; Logger().WriteFormat(_L("Attempting to Open %d sockets"), KNumStretchOpens); for (i=0; i<KNumStretchOpens; i++) { ret = sockets[i].Open(ss, protoInfo.iAddrFamily, protoInfo.iSockType, protoInfo.iProtocol); if (KErrNone != ret) { Logger().WriteFormat(_L("Open returned %S for socket %d"), &EpocErrorToText(ret), i); TESTL(EFalse); } } Logger().WriteFormat(_L("Closing the first %d sockets"), KNumStretchOpens-1); for (i=0; i<KNumStretchOpens-1; i++) { sockets[i].Close(); } RSocket sock; TInt failure = 0; ret = -1; Logger().WriteFormat(_L("Starting OOM Socket Open Loop")); // ss.__DbgMarkHeap(); // in ESOCKMT leak checking is best done by shutting down the server while (ret != KErrNone) { Logger().WriteFormat(_L("Failing after %d allocs"), failure); ss.__DbgFailNext(failure); ret = sock.Open(ss, protoInfo.iAddrFamily, protoInfo.iSockType, protoInfo.iProtocol); // if (ret != KErrNone) // { // ss.__DbgCheckHeap(0); // } failure++; } Logger().WriteFormat(_L("Created socket OK")); sockets[KNumStretchOpens-1].Close(); CleanupStack::PopAndDestroy(sockets); sock.Close(); // ss.__DbgMarkEnd(0); // Flush any FailNext there might be hanging around. ss.__DbgFailNext(-1); CleanupStack::Pop(&ss); ss.Close(); #else Logger().WriteFormat(_L("TestDisabled on release build.")); verdict = EInconclusive; #endif SetTestStepResult(verdict); return verdict; }
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(); }
/** * List existing network interfaces, IP addresses bound to them * and fill up array of IP addresses for all interfaces. */ void CTestStepLLMNR_Init::ListInterfacesL() { RSocket socket; TInt nRes; TInt exceed; TInt idx; TName tmpBuf; TName tmpBuf1; nRes = socket.Open(ipTestServer->iSocketServer, KAfInet, KSockStream, KProtocolInetTcp); TESTL(nRes == KErrNone); TUint bufsize = 2048; HBufC8 *buffer =NULL; buffer = GetBuffer(buffer, bufsize); TESTL(buffer != NULL); TPtr8 bufdes = buffer->Des(); //-- reset array of local addresses ipTestServer->iLocalAddrs.Reset(); //-- list all available network interfaces INFO_PRINTF1(KNewLine); INFO_PRINTF1(_L("--- available network interfaces:")); do {//-- get list of network interfaces // if exceed>0, all interface could not fit into the buffer. // In that case allocate a bigger buffer and retry. // There should be no reason for this while loop to take more than 2 rounds. bufdes.Set(buffer->Des()); exceed = socket.GetOpt(KSoInetInterfaceInfo, KSolInetIfQuery, bufdes); if(exceed > 0) { bufsize += exceed * sizeof(TInetInterfaceInfo); buffer = GetBuffer(buffer, bufsize); TESTL(buffer != NULL); } } while (exceed > 0); if (exceed < 0) { INFO_PRINTF1(_L("socket.GetOpt() error!")); TESTL(EFalse); } TOverlayArray<TInetInterfaceInfo> infoIface(bufdes); for(idx=0; idx < infoIface.Length(); ++idx) { TInetInterfaceInfo& iface = infoIface[idx]; tmpBuf.Format(_L("index:%d, name: "),iface.iIndex); tmpBuf.Append(iface.iName ); tmpBuf.AppendFormat(_L(" state:%d"), iface.iState); INFO_PRINTF1(tmpBuf); } //-- list all IP addresses, bound to the interfaces //-- and append this address to the array of host-local addresses INFO_PRINTF1(KNewLine); INFO_PRINTF1(_L("--- IP addresses bound to the interfaces:")); do { // if exceed>0, all interface could not fit into the buffer. // In that case allocate a bigger buffer and retry. // There should be no reason for this while loop to take more than 2 rounds. bufdes.Set(buffer->Des()); exceed = socket.GetOpt(KSoInetAddressInfo, KSolInetIfQuery, bufdes); if(exceed > 0) { bufsize += exceed * sizeof(TInetAddressInfo); buffer = GetBuffer(buffer, bufsize); } } while (exceed > 0); if (exceed < 0) { INFO_PRINTF1(_L("socket.GetOpt() error!")); TESTL(EFalse); } //-- print out IP addresses TOverlayArray<TInetAddressInfo> infoAddr(bufdes); TInetAddr inetAddr; for(idx=0; idx < infoAddr.Length(); ++idx) { TInetAddressInfo& addr = infoAddr[idx]; tmpBuf.Format(_L("iface index: %d, scopeID: %d, state: %d, IP addr: "), addr.iInterface, addr.iScopeId, addr.iState); inetAddr.SetAddress(addr.iAddress); inetAddr.Output(tmpBuf1); tmpBuf.Append(tmpBuf1); INFO_PRINTF1(tmpBuf); //-- if obtained IP address is valid and not loopback, add it to the array. if(inetAddr.IsLoopback() || inetAddr.IsUnspecified()) {} else ipTestServer->iLocalAddrs.Append(inetAddr); } delete buffer; socket.Close(); INFO_PRINTF1(KNewLine); }
void CTestStepESockSSA::DoDataThreadL(TDataThreadControl& aControl) { User::LeaveIfError(aControl.iSession.Connect()); // Wait for blocker to start blocking; we can then create an IP socket as it will have already loaded RProperty blockProp; TInt err = blockProp.Attach(TBlockerSID, CBlockerChannelHandler::EBlockingStateKey); if(err == KErrNone) { TRequestStatus status; do { blockProp.Subscribe(status); TInt blockState; err = blockProp.Get(blockState); if(err != KErrNone || blockState >= CBlockerChannelHandler::EStateBlocking) { blockProp.Cancel(); } User::WaitForRequest(status); } while(status == KErrNone); blockProp.Close(); } switch(aControl.iRequest) { case TDataThreadControl::ESocketOpen: { RSocket sock; User::LeaveIfError(sock.Open(aControl.iSession, KAfInet, KSockDatagram, KProtocolInetUdp)); sock.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = sock.Open(aControl.iSession, KDummyOneName); // should block sock.Close(); break; } case TDataThreadControl::EHostResolverOpen: { RHostResolver hr; hr.Open(aControl.iSession, KAfInet, KProtocolInetUdp); hr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = hr.Open(aControl.iSession, KDummyAddrFamily, KDummyOne); // should block hr.Close(); break; } case TDataThreadControl::EHostResolverOpenMulti: { RHostResolver hr; aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = hr.Open(aControl.iSession, KDummyAddrFamily, KDummyOne); // should block hr.Close(); break; } case TDataThreadControl::EServiceResolverOpen: { RServiceResolver sr; sr.Open(aControl.iSession, KAfInet, KSockDatagram, KProtocolInetUdp); sr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = sr.Open(aControl.iSession, KDummyAddrFamily, KSockDatagram, KDummyOne); // should block sr.Close(); break; } case TDataThreadControl::ENetDBOpen: { RNetDatabase ndb; ndb.Open(aControl.iSession, KAfInet, KProtocolInetUdp); ndb.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = ndb.Open(aControl.iSession, KDummyAddrFamily, KDummyOne); // should block ndb.Close(); break; } case TDataThreadControl::ENumProtocols: { TUint numOfProtocols; aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = aControl.iSession.NumProtocols(numOfProtocols); // should block break; } case TDataThreadControl::EGetProtocolInfo: { TUint absentIndex = 99; TProtocolDesc protocolDesc; RHostResolver hr; hr.Open(aControl.iSession, KAfInet, KProtocolInetUdp); hr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = aControl.iSession.GetProtocolInfo(absentIndex, protocolDesc); // should block break; } case TDataThreadControl::EFindProtocol: { _LIT(KAbsentProtocolName,"NoSuchProtocol"); TProtocolDesc protocolDesc; RHostResolver hr; hr.Open(aControl.iSession, KAfInet, KProtocolInetUdp); hr.Close(); aControl.iBlocked = ETrue; aControl.iBlockSemaphore.Signal(1); aControl.iResult = aControl.iSession.FindProtocol(KAbsentProtocolName(), protocolDesc); // should block break; } default: ASSERT(0); } }
/** * 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); }
TVerdict CPPPMinMaxMMU::doTestStepL() { const TInt KMaxMMU = 4000; const TInt KMinMMU = 1; TBuf8<KMaxMMU> *sendBuf = new(ELeave) TBuf8<KMaxMMU>(); CleanupStack::PushL(sendBuf); TBuf8<KMaxMMU> *recvBuf = new(ELeave) TBuf8<KMaxMMU>(); CleanupStack::PushL(recvBuf); TBuf8<KMaxMMU> *recvBuf2 = new(ELeave) TBuf8<KMaxMMU>(); CleanupStack::PushL(recvBuf2); //initialize COMM //CommInitL(EFalse); //Start Comms server // _LIT(KPhbkSyncCMI, "phbsync.cmi"); // (void)StartC32WithCMISuppressions(KPhbkSyncCMI); SetTestStepResult(EPass); INFO_PRINTF1(_L("Starting: Socket Server\n")); RSocketServ ss; // Start the socket server TEST(KErrNone == ss.Connect()); RSocket sock; TRequestStatus sta; INFO_PRINTF1(_L("Open a socket\n")); // Get the test address TInetAddr RemAddr(7); TPtrC testAddr; TEST(GetStringFromConfig(_L("AddressInfo"), _L("TestPPPIPAddr"), testAddr)); if(testAddr.Length()) { RemAddr.Input(testAddr); } else { INFO_PRINTF1(_L("Test FAILED\nMissing address information in config file: ")); return EFail; } // Open a socket TEST(KErrNone == sock.Open(ss, KAfInet, KSockStream, KProtocolInetTcp)); INFO_PRINTF1(_L("Connecting Socket to:")); TBuf<30> printAddr; RemAddr.Output(printAddr); INFO_PRINTF1(printAddr); // Connect a socket sock.Connect(RemAddr,sta); // Wait for Connect to complete User::WaitForRequest(sta); TEST(sta.Int() == 0); TInt iterEnd; GetIntFromConfig(_L("MMUInfo"), _L("TestPPPmaxMMU"), iterEnd); if (iterEnd > KMaxMMU) iterEnd = KMaxMMU; TInt iterStart; GetIntFromConfig(_L("MMUInfo"), _L("TestPPPminMMU"), iterStart); if (iterStart < KMinMMU) iterStart = KMinMMU; TInt i,j; TSockXfrLength recvLen; INFO_PRINTF1(_L("Send/Recv frames")); for(j=iterStart;j<=iterEnd;j++) { sendBuf->Zero(); for (i=0;i<j;i++) sendBuf->Append(Math::Random() & 0x7f); INFO_PRINTF2(_L("Sending Packet of Size: %d"),j); // Send data to echo port sock.Write(*sendBuf,sta); User::WaitForRequest(sta); TEST(sta.Int() == 0); i=0; recvBuf->Zero(); while(i<j) { // Receive data from echo port sock.RecvOneOrMore(*recvBuf2,0,sta,recvLen); User::WaitForRequest(sta); TEST(sta.Int() == 0); i += recvBuf2->Length(); recvBuf->Append(*recvBuf2); } TEST(KErrNone == recvBuf->Compare(*sendBuf)); INFO_PRINTF1(_L(" Received echoed Packet")); } sock.Shutdown(RSocket::EStopOutput,sta); User::WaitForRequest(sta); TEST(sta.Int() == 0); sock.Close(); ss.Close(); CleanupStack::PopAndDestroy(3); return TestStepResult(); }