enum TVerdict CEsockTest19_1::easyTestStepL() { TInetAddr addr; TBuf<39> buf; // setting the IP address const TIp6Addr KInet6Addr19_1 = {{{0xff,0xfe,0,0,0,0,0,0,0,0,0,0,0,0,0x29,0xfe}}}; const TIp6Addr KInet6Addr19_2 = {{{0xff,0xf1,0,1,0,1,0,1,0,1,0,1,0,1,0x29,0xff}}}; // setting the IP address // set the address addr.SetAddress(KInet6Addr19_1); // check it has been set correctly addr.OutputWithScope(buf); TESTL(buf==_L("fffe::29fe")); // check port number initialised to 0 TESTL(addr.Port()==0); // change the address addr.SetAddress(KInet6Addr19_2); // check it has been set correctly addr.OutputWithScope(buf); TESTL(buf==_L("fff1:1:1:1:1:1:1:29ff")); // check port number is still set to 0 TESTL(addr.Port()==0); return EPass; }
/** * Function that takes an IP address from user input, accesses the * Bluetooth PAN Profile table in the CommDb and updates the IpAddr * field with the supplied address. */ void CPanConnections::SetLocalIpAddrL(TUint32 addr) { iLocalIpAddr = addr; iSrcAddr.SetAddress(iLocalIpAddr); CCommsDatabase* db = CCommsDatabase::NewL(); CleanupStack::PushL(db); // Get the LAN service table CCommsDbTableView* tableView = db->OpenTableLC(TPtrC(LAN_SERVICE)); TBuf<KMaxBufferSize> tableName; TInt err = tableView->GotoFirstRecord(); if(err == KErrNone) { // Get the name of the table tableView->ReadTextL(TPtrC(COMMDB_NAME), tableName); if(tableName == TPtrC(_S("BluetoothPANProfile"))) { TInetAddr tempAddr; TBuf<KMaxBufferSize> dispBuf; tempAddr.SetAddress(iLocalIpAddr); tempAddr.Output(dispBuf); User::LeaveIfError(tableView->UpdateRecord()); tableView->WriteTextL(_L("IpAddr"), dispBuf); User::LeaveIfError(tableView->PutRecordChanges()); User::LeaveIfError(db->CommitTransaction()); } } else { User::Leave(KErrNotFound); } CleanupStack::PopAndDestroy(2);//db & tableView }
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); } }
// --------------------------------------------------------------------------- // CNATFWStunConnectionHandler::FetchCandidateL // --------------------------------------------------------------------------- // void CNATFWStunConnectionHandler::FetchCandidateL( TUint aStreamId, TUint /*aRtoValue*/, TUint /*aAddrFamily*/, const TInetAddr& aBaseAddr ) { __STUNPLUGIN( "CNATFWStunConnectionHandler::FetchCandidateL start" ) // Store data in array TStreamData streamData; streamData.iStreamId = aStreamId; CNATFWCandidate* newCandidate = CNATFWCandidate::NewLC(); TInetAddr publicAddr; if ( KAfInet6 == aBaseAddr.Family() ) { const TIp6Addr KIp6Addr = {{{1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,1}}}; publicAddr.SetAddress( KIp6Addr ); } else { publicAddr.SetAddress( INET_ADDR( 1,2,3,4 ) ); } // Set candidate parameters newCandidate->SetStreamId( aStreamId ); newCandidate->SetType( CNATFWCandidate::EServerReflexive ); newCandidate->SetTransportAddrL( publicAddr ); newCandidate->SetTransportProtocol( KProtocolInetUdp ); TConnectionData connData; connData.iLocalCandidate = newCandidate; streamData.iConnArray.AppendL( connData ); iStreamArray.AppendL( streamData ); TCallBackCmd cmd = TCallBackCmd( aStreamId, EFetchCandidate, 0, newCandidate ); iCallBackCmds.AppendL( cmd ); CleanupStack::Pop( newCandidate ); if ( !IsActive() ) { After( KWaitTime ); } // wait MNcmConnectionObserver::ConnectionNotify __STUNPLUGIN( "CNATFWStunConnectionHandler::FetchCandidateL end" ) }
/** * 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; }
/** * Function to print the current connections we have. */ void CPanConnections::PrintConns() { iConsole.Printf(_L("\nRemotenames : %d\n"), iRemoteNames.Count()); PrintTcpSocketConnections(); iConsole.Printf(_L("--------------------------------------------------\n")); iConsole.Printf(_L("Listening Mode: ")); iListening ? iConsole.Printf(_L("Enabled ")) : iConsole.Printf(_L("Disabled ")); if(iIapStarted) { iConsole.Printf(_L(" IAP Started")); TInt err = UpdateCurrentConnections(); if(err != KErrNone) { iConsole.Printf(_L("FAILED TO ENUMERATE CONNECTIONS. Err %d\n"), err); } else { iConsole.Printf(_L("\n------------------ CONNECTIONS -------------------\n")); iConsole.Printf(_L("Index Remote Addr\n")); for(TInt i=0;i<iActiveConnections.Count();i++) { TBuf<KMaxBufferSize> dispBuf; iActiveConnections[i].GetReadable(dispBuf); if(iActivePanConn == i) { iConsole.Printf(_L("-> ")); } else { iConsole.Printf(_L(" ")); } iConsole.Printf(_L("%d 0x%S\n"), i, &dispBuf); } } } if(iLocalIpAddr == 0) { iConsole.Printf(_L("\nNo local IP address set\n")); } else { TInetAddr tempAddr; TBuf<KMaxBufferSize> dispBuf; tempAddr.SetAddress(iLocalIpAddr); tempAddr.Output(dispBuf); iConsole.Printf(_L("\nLocal IP address: %S\n"), &dispBuf); } }
void HXSymbianTCPConnector::Connect(RSocket& socket, ULONG32 ulAddr, UINT16 nPort) { m_addr.SetAddress(ulAddr); m_addr.SetPort(nPort); iStatus = KRequestPending; socket.Connect(m_addr, iStatus); SetActive(); }
void CFTPResolver::SetAddress(TInetAddr& aAddress) { // Get the 1st entry resolved iNameRecord = iNameEntry(); // Save the address (take care not to overwrite the port, might have been already set) if (TInetAddr::Cast(iNameRecord.iAddr).Family() == KAfInet) aAddress.SetAddress(TInetAddr::Cast(iNameRecord.iAddr).Address()); else aAddress.SetAddress(TInetAddr::Cast(iNameRecord.iAddr).Ip6Address()); #if defined(__FTPPROTDEBUG__) TBuf<512> debugBuffer; // A Buffer to output the resolved IP aAddress.Output(debugBuffer); debugBuffer.Append(_L(",")); debugBuffer.AppendNum(aAddress.Port(), EDecimal); debugBuffer.Append(_L("\n")); #endif FTPPROTDEBUG(_DBGResolver,_L("Resolved address is:")); FTPPROTDEBUG(_DBGResolver,debugBuffer); }
TBool CDHCPOptionDNSServers::GetDomainNameServer( TInt aIndex, TInetAddr& addr ) { TInt pos = aIndex * KIp6AddressLength; TBool ret = GetLength() >= pos + KIp6AddressLength; if ( ret ) { // Must ensure IP6 address is word aligned! So declare it locally TIp6Addr ip6addr; Mem::Copy(&ip6addr,GetBodyPtr() + pos,KIp6AddressLength); addr.SetAddress(ip6addr); } return ret; }
void CDnsResolver::Resolve(const TDesC& aHostName) { if (IsActive()) { User::Invariant(); return; } _LIT(KLocalHostName, "localhost"); if (aHostName == KLocalHostName) { const TUint32 KLocalIpAddr = INET_ADDR(127,0,0,1); TInetAddr localIpAddr; localIpAddr.SetAddress(KLocalIpAddr); iNameEntry().iAddr = localIpAddr; // copy iStatus = KRequestPending; SetActive(); TRequestStatus* status = &iStatus; User::RequestComplete(status, KErrNone); return; } // ensure that we have a resolver session we can use if (!IS_SUBSESSION_OPEN(iHostResolver)) { TInt error; if (iConnection) { error = iHostResolver.Open(iSocketServ, KAfInet, KProtocolInetUdp, *iConnection); } else { error = iHostResolver.Open(iSocketServ, KAfInet, KProtocolInetUdp); } if (error != KErrNone && error != KErrAlreadyExists) { iStatus = KRequestPending; SetActive(); TRequestStatus* status = &iStatus; User::RequestComplete(status, error); return; } } SET_SESSION_OPEN(iHostResolver); iHostResolver.GetByName(aHostName, iNameEntry, iStatus); SetActive(); }
enum TVerdict CEsockTest17_7::easyTestStepL() { // // IsWildPort() // // TInetAddr addr; addr.SetAddress(IPADDR(126,0,0,1)); addr.SetPort(0); // IP Address to 126,0,0,1 and Port to Zero TESTL(addr.IsWildPort()!=EFalse); // Port = 0 - True addr.SetPort(21); // Sets Port to 21 FTP TESTL(addr.IsWildPort()==EFalse); // Port = 21 - False addr.SetAddress(IPADDR(191,220,145,22)); // IP Address to 191.220.145.22 TESTL(addr.IsWildPort()==EFalse); // Port = 21 - False addr.SetPort(0); // Sets Port to 0 TESTL(addr.IsWildPort()!=EFalse); // Port = 0 - True return EPass; }
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 }
void CQoSMsg::AddSrcAddr(const TInetAddr &aAddr) /** Adds Source Address Information to the QoS PRT Message @param aAddr Source Address */ { TInetAddr srcInetAddr(aAddr); srcInetAddr.SetFamily(KAFUnspec); srcInetAddr.SetAddress(KInet6AddrNone); TInetAddr mask; mask.SetAddress(KInet6AddrMask); iMsg->AddSrcAddress(srcInetAddr, mask, (TUint16)srcInetAddr.Port()); }
void CQoSMsg::AddDstAddr(const TInetAddr &aAddr) /** Adds Destination Address Information to the QoS PRT Message @param aAddr Destination Address */ { TInetAddr dstInetAddr(aAddr); if (dstInetAddr.Family() == KAfInet) { dstInetAddr.ConvertToV4Mapped(); } TInetAddr mask; mask.SetAddress(KInet6AddrMask); iMsg->AddDstAddress(dstInetAddr, mask, (TUint16)dstInetAddr.Port()); }
TBool CDHCPOptionSipServerAddrs::GetSipServerAddr(TInt aIndex, TInetAddr& addr) { __CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("CDHCPOptionSipServerAddrs::GetSipServerAddr index = %d"),aIndex)); TInt pos = aIndex * KIp6AddressLength; TInt len = GetLength(); TBool ret = len >= pos + KIp6AddressLength; __CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("pos = %d, len = %d, ret = %d"), pos, len, ret)); if (ret) { // Must ensure IP6 address is word aligned! So declare it locally TIp6Addr ip6addr; Mem::Copy(&ip6addr,GetBodyPtr() + pos,KIp6AddressLength); addr.SetAddress(ip6addr); } return ret; }
void UT_CNATTraversalController::TestUpdateNextHopL() { // No binding iController->UpdateNextHop(iNextHopAddr, this); // Binding exists, same next hop TBool dummy(EFalse); CNATTraversalConfig* config = CNATTraversalConfig::NewLC(KIapId,KDomain); iController->CreateBindingL(1,config,iConnection,iLocalAddr,iSocket, iNextHopAddr,*this,*this,dummy); CleanupStack::Pop(config); iController->UpdateNextHop(iNextHopAddr, this); EUNIT_ASSERT(iController->iSessions[0]->iNextHopAddr.CmpAddr(iNextHopAddr)); // Binding exists, next hop changes TInetAddr newNextHop; newNextHop.SetAddress(INET_ADDR(123,123,123,123)); iController->UpdateNextHop(newNextHop, this); EUNIT_ASSERT(iController->iSessions[0]->iNextHopAddr.CmpAddr(newNextHop)); }
// resolves a name synchronously, returning an error code TInt Resolve(RSocketServ& aSocketServ, const TDesC& aHostName, TSockAddr& aResult) { // This is a special case that it looks like the resolver // cannot handle. It is also common enough for this code // to perhaps improve efficiency, as we do not require // a resolver session. _LIT(KLocalHostName, "localhost"); if (aHostName == KLocalHostName) { const TUint32 KLocalIpAddr = INET_ADDR(127,0,0,1); TInetAddr localIpAddr; localIpAddr.SetAddress(KLocalIpAddr); aResult = localIpAddr; // copy return KErrNone; } RHostResolver resolver; TInt error = resolver.Open(aSocketServ, KAfInet, KProtocolInetUdp); if (error) { return error; } TNameEntry nameEntry; TRequestStatus resolvStatus; resolver.GetByName(aHostName, nameEntry, resolvStatus); User::WaitForRequest(resolvStatus); error = resolvStatus.Int(); resolver.Close(); if (error) { return error; } TNameRecord record = nameEntry(); TSockAddr& addr = record.iAddr; aResult = addr; // copy return KErrNone; }
// // Start asynchronous recv() operation // pj_status_t CIoqueueCallback::StartRead (pj_ioqueue_op_key_t *op_key, void *buf, pj_ssize_t *size, unsigned flags, pj_sockaddr_t *addr, int *addrlen) { PJ_ASSERT_RETURN (IsActive() ==false, PJ_EBUSY); PJ_ASSERT_RETURN (pending_data_.common_.op_key_==NULL, PJ_EBUSY); flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; pending_data_.read_.op_key_ = op_key; pending_data_.read_.addr_ = addr; pending_data_.read_.addrlen_ = addrlen; aBufferPtr_.Set ( (TUint8*) buf, 0, (TInt) *size); type_ = TYPE_READ; if (addr && addrlen) { sock_->Socket().RecvFrom (aBufferPtr_, aAddress_, flags, iStatus); } else { aAddress_.SetAddress (0); aAddress_.SetPort (0); if (sock_->IsDatagram()) { sock_->Socket().Recv (aBufferPtr_, flags, iStatus); } else { // Using static like this is not pretty, but we don't need to use // the value anyway, hence doing it like this is probably most // optimal. static TSockXfrLength len; sock_->Socket().RecvOneOrMore (aBufferPtr_, flags, iStatus, len); } } SetActive(); return PJ_EPENDING; }
void UT_CMceSecureDesStream::SetupL( ) { //Set up the basic iSession = MceMediaManagerTestHelper::CreateMultimediaOutSessionL(); RPointerArray<CMceComMediaStream>& streams = iSession->Streams(); TInt count=streams.Count(); if (count>0) { iStream1=streams[0]; } if (count>1) { iStream2=streams[1]; } iMcc = CMccControllerStub::Stub(); iManager = CMceMediaManager::NewL( *this ); RPointerArray<CMceComAudioCodec> audioCapabilities; RPointerArray<CMceComVideoCodec> videoCapabilities; MceCleanupResetAndDestroyPushL( audioCapabilities ); MceCleanupResetAndDestroyPushL( videoCapabilities ); iManager->GetCapabilitiesL( audioCapabilities ); iManager->GetCapabilitiesL( videoCapabilities ); CleanupStack::PopAndDestroy( 2 );//capas __ASSERT_ALWAYS( iManager->iSdpCodecs.Count() >= 2, User::Leave( KErrNotFound ) ); iAudioSdpCodec = static_cast<CMceMediaSdpCodec*>( iManager->iSdpCodecs[ 0 ] ); iVideoSdpCodec = static_cast<CMceMediaSdpCodec*>( iManager->iSdpCodecs[ 1 ] ); iAudio = SdpCodecStringPool::StringPoolL().StringF( SdpCodecStringConstants::EMediaAudio, SdpCodecStringPool::StringTableL()); iVideo = SdpCodecStringPool::StringPoolL().StringF( SdpCodecStringConstants::EMediaVideo, SdpCodecStringPool::StringTableL()); iProtocol = SdpCodecStringPool::StringPoolL().StringF( SdpCodecStringConstants::EProtocolRtpAvp, SdpCodecStringPool::StringTableL() ); // Create media line: m= This should correspond to the OFFER received! iMedia = CSdpMediaField::NewLC ( iVideo, 8000, iProtocol, _L8("96") ); // Note the sendrcv, this should create bound stream as well since it's two way. RStringF attribute = SdpCodecStringPool::StringPoolL().StringF ( SdpCodecStringConstants::EAttributeSendrecv, SdpCodecStringPool::StringTableL() ); CSdpAttributeField* mediaAttr = CSdpAttributeField::NewLC(attribute, _L8("")); iMedia->AttributeFields().AppendL( mediaAttr ); attribute.Close(); CleanupStack::Pop( mediaAttr ); CleanupStack::Pop( iMedia ); TUint payloadType = 96; // Get the encoding name TPtrC8 codecName = _L8("HMMH"); TUint clockRate = 90000; // create rtpmap field for current codec CSdpFmtAttributeField* rtpmapAttribute = iVideoSdpCodec->EncodeRtpMapFieldsL( payloadType, codecName, clockRate, KMceSdpOptionalEncodingParam ); CleanupStack::PushL( rtpmapAttribute ); iMedia->FormatAttributeFields().AppendL( rtpmapAttribute ); CleanupStack::Pop( rtpmapAttribute ); iOffer = CSdpDocument::NewL(); CleanupStack::PushL( iOffer ); iOffer->MediaFields().AppendL( iMedia ); // Set session name: s= iOffer->SetSessionNameL( _L8("") ); const TUint32 KInetAddr = INET_ADDR(10,10,10,10); TInetAddr localIpAddress; localIpAddress.SetAddress(KInetAddr); CSdpOriginField* originField = CSdpOriginField::NewL( _L8("username"), 55555, 55555, localIpAddress ); iOffer->SetOriginField( originField ); // Create connection field: c= CSdpConnectionField* connectionField = CSdpConnectionField::NewL( localIpAddress ); iOffer->SetConnectionField( connectionField ); CleanupStack::Pop( iOffer ); iInterface = CMccInterface::NewL( *iManager ); iSecureInterface= CMccSecureInterface::NewL( *iInterface ); iSecureSession = CMceSecureMediaSession::NewL( *iSession, *iManager, *iSecureInterface ); iSecureStream = CMceSecureDesStream::NewL( *iSecureSession, *iMedia, *iSecureInterface, *iStream1 ); iSecureStream->AppendEmptyCryptoL( *iSecureStream->iCryptoOuts, KTotalCryptoAnswerCount ); }
TBool Ikev2MobIke::ProcessNotifysL(CIkev2Negotiation* aNegotiation, const CArrayFixFlat<TNotifPayloadIkev2*>& aNotifys, TBool aRequest, TInt aExchange) { __ASSERT_DEBUG(aNegotiation, User::Invariant()); if ( !aNegotiation->iHdr.iIkeData->iUseMobIke ) { return EFalse; } TInt MsgType; TNotifPayloadIkev2* Payload; TPtrC8 Cookie2(NULL,0); TBool NatDetection = EFalse; TBool Status = EFalse; TInt Count = aNotifys.Count(); TInt i = 0; while ( i < Count ) { Payload = aNotifys.At(i); MsgType = (TInt)Payload->GetMsgType(); // // Process possible MOBIKE Notify messages // switch ( MsgType ) { case MOBIKE_SUPPORTED: // // Remote end supports MOBIKE protocol // aNegotiation->iHdr.iMobikeUsed = ETrue; aNegotiation->iHdr.iFloatedPort = ETrue; // Floated port used for now aNegotiation->iHdr.iDestinAddr.SetPort(FLOATED_IKE_PORT); break; case ADDITIONAL_IPV4_ADDRESS: case ADDITIONAL_IPV6_ADDRESS: // // Additional IP addresses Notify // if ( aNegotiation->iHdr.iMobikeUsed && (aExchange == INFORMATIONAL) ) { Status = ETrue; } break; case UPDATE_SA_ADDRESS: // // Peer informs about the IP address change // if ( aNegotiation->iHdr.iMobikeUsed && aRequest && (aExchange == INFORMATIONAL) ) { aNegotiation->iIkeV2PlugInSession.RemoteAddrChanged(&aNegotiation->iHdr, aNegotiation->iHdr.iDestinAddr); Status = ETrue; } break; case COOKIE2: // // Peer informs about the IP address change // if ( aNegotiation->iHdr.iMobikeUsed && aRequest && (aExchange == INFORMATIONAL) ) { Cookie2.Set(Payload->NotifData(), Payload->NotifDataLength()); Status = ETrue; } break; case NAT_PREVENTION: // // NAT Prevention Notify // if ( aNegotiation->iHdr.iMobikeUsed ) { if ( aExchange == INFORMATIONAL ) Status = ETrue; } break; case UNACCPETABLE_ADDRESSES: case NAT_PREVENTED: if ( aNegotiation->iHdr.iMobikeUsed ) { if ( aExchange == INFORMATIONAL ) Status = ETrue; } break; case NAT_DETECTION_SOURCE_IP: case NAT_DETECTION_DESTINATION_IP: if ( aNegotiation->iHdr.iMobikeUsed && (aExchange == INFORMATIONAL)) { NatDetection = ETrue; Status = ETrue; } break; default: break; } i ++; } if ( Status && aRequest && (aExchange == INFORMATIONAL) ) { // // Build informational response to MOBIKE request // CIkeV2Message* ikeMsg = CIkeV2Message::NewL(aNegotiation->iHdr.SpiI(), aNegotiation->iHdr.SpiR(), INFORMATIONAL, aNegotiation->iHdr.iInitiator, ETrue, aNegotiation->iHdr.ExpectedRequestId(), aNegotiation->iDebug); ikeMsg->AppendEncryptedPayloadL(aNegotiation->iHdr.iCipherBlkLth); if ( Cookie2.Ptr() ) { // // Peer is using COOKIE2. Return COOKIE2 payload data as such // ikeMsg->AppendNotifyPayloadL(IKEV2_PROTOCOL, KZeroDesc, COOKIE, Cookie2); } if ( NatDetection ) { // // Peer is using NAT_DETECTION_*_IP payloads. Build corresponding response // TBool NatDetectOk; TInetAddr DummyIp; DummyIp.SetAddress(KInetAddrNone); // 0.0.0.0 TUint32 NATFlags = CIkev2NatT::CheckPeerNotifysL(aNotifys, DummyIp, aNegotiation->iHdr.iDestinAddr, FLOATED_IKE_PORT, ikeMsg->InitiatorSpi(), ikeMsg->ResponderSpi(), NatDetectOk); if ( NatDetectOk ) { aNegotiation->iHdr.iNATFlags = NATFlags; aNegotiation->GetNatStatus(NatDetectOk, aNegotiation->iHdr.iDestinAddr); } CIkev2NatT* NatNotify = CIkev2NatT::NewL(DummyIp, aNegotiation->iHdr.iDestinAddr, FLOATED_IKE_PORT, ikeMsg->InitiatorSpi(), ikeMsg->ResponderSpi()); CleanupStack::PushL(NatNotify); ikeMsg->AppendNotifyPayloadL(IKEV2_PROTOCOL, KZeroDesc, NAT_DETECTION_SOURCE_IP, NatNotify->SourceNofify()); ikeMsg->AppendNotifyPayloadL(IKEV2_PROTOCOL, KZeroDesc, NAT_DETECTION_DESTINATION_IP, NatNotify->DestinNofify()); CleanupStack::PopAndDestroy(NatNotify); } aNegotiation->SendIkeMsgL(ikeMsg); aNegotiation->iIkeV2PlugInSession.UpdateIkev2SAL(&aNegotiation->iHdr, NULL); if ( (aNegotiation->iState != KStateIkeInfoRequest) && (aNegotiation->iState != KStateIkeDeleteRequest) && (aNegotiation->iState != KStateIkeDeleteResponse) ) aNegotiation->iState = KStateIkeSaCompleted; } // // else // Currently there is no need to examine any MOBIKE Notify payloads // present in Informational response // return Status; }
TInt CTS_MultiHomingStep::GetSockConfig(const TInt aIndex, TInt& aProtocol, TInt& aPackSize, TInt& aNumPackets, TInt& aUdp, TInetAddr& aDstAddr, TInetAddr& aSrcAddr, TBool& aExpectSuccess, TBool& aIsListener, TConnDetails **aConnDetails) /** * Gets socket configuration from file, using defaults if necessary * @param aIndex The index for the socket configkey * @param aProtocol The protocol to be used * @param aPackSize The packet size in bytes * @param aNumPackets Number of packets to send * @param aUdp Percentage of UDP packets that can be dropped * @param aAddr The destination address for the socket * @param aSS The socket server sub-session to use for the socket * @param aNetName The network connection name in the suite * @return System wide error code */ { TInt err=KErrNone; TInt val=0; TBuf<10> socketNum; // Create the Key for the config lookup socketNum= KSocket; socketNum.AppendNum(aIndex); TPtrC ptrBuf; // Port 0 means we dont care about binding to port err = GetStringFromConfig(socketNum, KSrcAddr, ptrBuf); if (err) { // String found in table err = aSrcAddr.Input(ptrBuf); TESTE(err==KErrNone,err); if (err !=KErrNone) { iTestStepResult= EInconclusive; return KErrBadName; } } else aSrcAddr.SetAddress(KInetAddrAny); err = GetIntFromConfig(socketNum, KSrcPort, val); if (err) aSrcAddr.SetPort((TUint) val); else aSrcAddr.SetPort(0); // Default to zero - ie source address NOT uses err = GetStringFromConfig(socketNum, KDestAddr, ptrBuf); if (!err) { LogExtra((TText8*)__FILE__, __LINE__, ESevrWarn, KEConfigFile); iTestStepResult= EInconclusive; return KErrNotFound; } err = aDstAddr.Input(ptrBuf); TESTE(err==KErrNone,err); if (err !=KErrNone) { iTestStepResult= EInconclusive; return KErrBadName; } err = GetIntFromConfig(socketNum, KDestPort, val); if (!err) aDstAddr.SetPort(ECHO_PORT); // Default to echo port aDstAddr.SetPort((TUint) val); err = GetStringFromConfig(socketNum, KProtocol, ptrBuf); if (err && (ptrBuf.Compare(KTcp)==0)) aProtocol = KProtocolInetTcp; else aProtocol = KProtocolInetUdp; err = GetIntFromConfig(socketNum, KPacketSize, val); if (!err) aPackSize=PACKET_SIZE; aPackSize=val; err = GetIntFromConfig(socketNum, KNumOfPackets, val); if (!err) aNumPackets=NUM_OF_PACKETS; aNumPackets=val; err = GetIntFromConfig(socketNum, KUdpTol, val); if (!err) aUdp=UDP_TOLERANCE; aUdp=val; aExpectSuccess = ETrue; GetBoolFromConfig(socketNum, KExpectSuccess, aExpectSuccess); aIsListener = EFalse; GetBoolFromConfig(socketNum, KIsListener, aIsListener); err = GetStringFromConfig(socketNum, KConnName, ptrBuf); if (!err) { LogExtra((TText8*)__FILE__, __LINE__, ESevrWarn, KEConfigFile); iTestStepResult= EInconclusive; return KErrNotFound; } // Use default *aConnDetails = iOwnerSuite->GetTConnection(ptrBuf); return KErrNone; }
SYSCALL(MAHandle, maConnect(const char* url)) { TPtrC8 urlP(CBP url, SYSCALL_THIS->ValidatedStrLen(url)); LOGST("Connect %i %s", gConnNextHandle, url); if(gConnections.size() >= CONN_MAX) return CONNERR_MAX; _LIT8(KLocalhost, "localhost"); CConnection* conn = NULL; TPtrC8 match; SocketType socketType = TCP; // initialized to placate stupid compiler ConnectionType type; // determine type of connection if(SSTREQ(urlP, KSocket)) { match.Set(KSocket); type = eSocket; socketType = TCP; } else if(SSTREQ(urlP, KDatagram)) { match.Set(KDatagram); type = eSocket; socketType = UDP; } else if(SSTREQ(urlP, KSsl)) { match.Set(KSsl); type = eSocket; socketType = SSL; } else if(SSTREQ(urlP, KHttp)) { match.Set(KHttp); type = eHttp; socketType = TCP; } else if(SSTREQ(urlP, KHttps)) { match.Set(KHttps); type = eHttp; socketType = SSL; } else if(SSTREQ(urlP, KBtspp)) { match.Set(KBtspp); type = eBtspp; } else { //error return CONNERR_URL; } TPtrC8 parturl = urlP.Mid(match.Length()); if(type == eSocket) { TPtrC8 hostnamePtrC8; int port; if(!splitPurl(parturl, hostnamePtrC8, port, (1<<16))) { return CONNERR_URL; } Smartie<CSocket> sockp(createSocket(socketType)); _LIT8(K127, "127."); TInetAddr addr; bool localhost = false; if(hostnamePtrC8 == KLocalhost) { localhost = true; addr.SetAddress(INET_ADDR(127,0,0,1)); } else if(hostnamePtrC8.Length() > K127().Length()) { if(hostnamePtrC8.Left(K127().Length()) == K127) { localhost = true; Smartie<HBufC16> hostname(CreateHBufC16FromDesC8LC(hostnamePtrC8)); addr.Input(*hostname()); } } sockp->state |= CONNOP_CONNECT; if(localhost) { StartConnOpL(CO_AddrConnect::NewL(false, *this, gConnNextHandle, *sockp(), addr, port, *sockp())); } else { Smartie<HBufC16> hostname(CreateHBufC16FromDesC8LC(hostnamePtrC8)); CleanupStack::Pop(hostname()); StartConnOpL(CO_NameConnect::NewL(gNetworkingState != EStarted, *this, gConnNextHandle, *sockp(), hostname, port, *sockp())); } conn = sockp.extract(); } else if(type == eHttp) { CHttpConnection* http; TLTZ_PASS(httpCreateConnectionLC(parturl, http, HTTP_GET, socketType)); http->state |= CONNOP_CONNECT; StartConnOpL(CO_HttpFinish::NewL(gNetworkingState != EStarted, *this, gConnNextHandle, *http, *http, true)); http->mState = CHttpConnection::WRITING; conn = http; CleanupStack::Pop(conn); } else if(type == eBtspp) { if(gBtState != eAvailable) { return CONNERR_UNAVAILABLE; } TPtrC8 hostnamePtrC8; int port_m1_index = parturl.Locate(':'); if(port_m1_index == KErrNotFound) { return false; } hostnamePtrC8.Set(parturl.Left(port_m1_index)); if(hostnamePtrC8 == KLocalhost) { // server // extract and parse uuid static const int KUuidLength = 32; int uuidStartIndex = port_m1_index + 1; int paramStartIndex = uuidStartIndex + KUuidLength; if(parturl.Length() < paramStartIndex) { return CONNERR_URL; } TPtrC8 uuidPtrC8(parturl.Mid(uuidStartIndex, KUuidLength)); TUint32 us[4]; for(int i=0; i<4; i++) { TPtrC8 p(uuidPtrC8.Mid(i*8, 8)); for(int j=0; j<8; j++) { if(!TChar(p[j]).IsHexDigit()) return CONNERR_URL; } LHEL(TLex8(p).Val(us[i], EHex)); } TUUID uuid(us[0], us[1], us[2], us[3]); //TUUID uuid(KSerialPortUUID); //temp hack // create listener socket Smartie<CBtServerSocket> sockp(new (ELeave) CBtServerSocket(gBtSdpDB)); // extract name, if it's there. initialize the socket. TPtrC8 paramPtrC8(parturl.Mid(paramStartIndex)); _LIT8(KNameParam, ";name="); if(SSTREQ(paramPtrC8, KNameParam)) { TPtrC8 namePtrC8(paramPtrC8.Mid(KNameParam().Length())); sockp->init(gSocketServ, uuid, true, namePtrC8); } else if(paramPtrC8.Length() == 0) { sockp->init(gSocketServ, uuid, false); } else { return CONNERR_URL; } //skip the async/connect step gConnections.insert(gConnNextHandle, sockp.extract()); return gConnNextHandle++; } else { // client // extract port number int port; if(!splitPurl(parturl, hostnamePtrC8, port, 31)) { return CONNERR_URL; } TRfcommSockAddr rfcsa; // parse address TBTDevAddr btaddr; for(int i=0; i<BTADDR_LEN; i++) { TLex8 btaLex(parturl.Mid(i*2, 2)); int result = btaLex.Val(btaddr[i], EHex); if(result != KErrNone) return CONNERR_URL; } rfcsa.SetBTAddr(btaddr); // create socket Smartie<CSocket> sockp(new (ELeave) CSocket(gSocketServ, CSocket::ERfcomm)); sockp->state |= CONNOP_CONNECT; StartConnOpL(CO_AddrConnect::NewL(false, *this, gConnNextHandle, *sockp(), rfcsa, port, *sockp())); conn = sockp.extract(); } } CleanupStack::PushL(conn); gConnections.insert(gConnNextHandle, conn); CleanupStack::Pop(conn); return gConnNextHandle++; }
void CWin32Socket::ConvertAddress(const SOCKADDR_IN& aWinSockAddress, TInetAddr& aESockAddress) const { aESockAddress.SetAddress(htonl(aWinSockAddress.sin_addr.s_addr)); aESockAddress.SetPort(htons(aWinSockAddress.sin_port)); }
/** * 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); }
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; }