Главная » Просмотр файлов » Symbian OS Communications

Symbian OS Communications (779884), страница 41

Файл №779884 Symbian OS Communications (Symbian Books) 41 страницаSymbian OS Communications (779884) страница 412018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 41)

Note that Connect() doesn’t actually send any IPtraffic.184IP AND RELATED TECHNOLOGIESconst TUint32 KInetAddr = INET_ADDR(192,168,1,1);iAddr.SetAddress(KInetAddr);iAddr.SetPort(8080);iSock.Connect(iAddr, iStatus);SetActive();Applications that will only work on specific networks must supply anIAP ID as a connection preference to the RConnection API to makesure the correct IAP is started.One advantage of using Connect() is that it allows the applicationto specify a single remote IP address up front so the Send() method canbe used to send data instead of specifying the address in each send aspart of the SendTo() call. But this may not be appropriate if there aremultiple remote devices involved.TSockXfrLength iLen = 0; // class member variable...TInt flags = 0;sock.SendTo(KHelloWorld, addr, flags, iStatus, iLen);The flags parameter is unused for UDP sockets, and for datagram sockets in general the TSockXfrLength parameter will contain the numberof bytes actually sent once the send completes successfully.

Applicationsusing active objects must make sure that the TSockXfrLength has thesame lifetime as the duration of the active object (i.e., it should be a classmember, rather than a local variable).Because UDP is an unreliable protocol, datagrams may be discardedbefore leaving the device, for example, if the internal queue is filled.However, it is possible for an application to enforce that a send operationblocks rather than allows the queue to fill if it would result in packets beingdiscarded.

An example of this is where the implicit network connectionis started as the result of the application sending data – it could take anumber of seconds for the network connection to activate, during whichtime datagrams may be discarded if the queue fills (the write will completeas soon as the data is queued, so the application may continue to writedatagrams causing the queue to fill). To enforce that a send will block ifthe send queue is full so that datagrams aren’t discarded, the applicationcan set the KSoUdpSynchronousSend socket option:sock.SetOpt(KSolInetUdp, KSoUdpSynchronousSend, iStatus);Note, however, that apart from preventing datagrams being lost duringconnection startup, this option is of limited general use, as preventing thelocal device dropping datagrams still does not guarantee that they willnot be discarded by the network or the remote device.USING THE NETWORK CONNECTION185Receiving UDP datagrams is just as easy as sending.

If Connect()has been called on the socket, the Recv() variation can be used, elseRecvFrom() is needed so that the remote address is known. In this case,Connect() also acts to filter the received datagrams to ensure they arefrom the correct address.sock.Recv(iBuf, flags, iStatus);Again the flags parameter is not used. Recv() will complete oncea datagram has been received.

However, the receiving buffer must belarge enough to hold the entire datagram else the remaining data will belost. The version of Recv() using a TSockXfrLength is not valid fordatagrams.For an unconnected socket, applications need to use RecvFrom() tobe able to extract the IP address of the sending device:sock.RecvFrom(iBuf, iAddr, flags, iStatus);On successful completion, the iAddr parameter will contain the IPaddress and port number of the sending device.Note that it isn’t possible (or sensible) to use RecvOneOrMore() withUDP sockets, or datagram sockets in general, because the receive onlycompletes once an entire datagram has been received.Cancelling asynchronous operationsFor both TCP and UDP, all asynchronous operations can be cancelledusing the relevant Cancel. .

.() method. You should be aware that theusual rules for cancelling an asynchronous service apply though – namelythat calling Cancel() is a declaration that you are not interested in theresult of the operation, not a way of preventing the operation takingplace. For example, your data may already have been placed in anoutgoing queue by the time you call Cancel(), in which case all you’redoing is preventing the notification of the completion of operation fromoccurring.There is also a CancelAll() method which will cancel all outstanding asynchronous requests.

This is particularly useful when destroyingan object that can perform many different asynchronous operations on asocket without having to call all the individual Cancel. . . () methodsin the destructor.Getting the local IP addressOne of the (potentially many) IP addresses of a local interface can beretrieved from a socket using the LocalName() method:sock.LocalName(addr);186IP AND RELATED TECHNOLOGIESOn a device that has many network connections active, this will returnone of the IP addresses belonging to the connection associated withthe RConnection that was used to open the socket (or of the implicitconnection if no RConnection was used).6.4.4 How to use Secure Sockets in Symbian OSSecure sockets, or sockets supporting the secure sockets layer (SSL) andTransaction Layer Security (TLS), are supported on Symbian OS throughCSecureSocket API.

Secure sockets are familiar to most developers asthe basis for https:// connections. They provide a way for the clientto authenticate the server to which they are connecting, and provide anencrypted channel to prevent eavesdropping and alteration of the datatransferred. In some cases, secure sockets can also be used to prove theidentity of a client to a server – however this usage is far less commondue to the low number of client devices with an appropriate certificatethat could be used to identify them.The CSecureSocket API is used to secure an already open andconnected socket.

CSecureSocket is instantiated with a reference toan already connected RSocket and a relevant protocol name. TheCSecureSocket finds, loads and creates a secure socket of the correctimplementation.The main part of the CSecureSocket API looks like this:class CSecureSocket : public CBase{public:IMPORT_C static CSecureSocket* NewL(RSocket& aSocket,const TDesC&aProtocol);IMPORT_C void Close();IMPORT_C void Send(const TDesC8& aDesc, TRequestStatus& aStatus,TSockXfrLength& aLen);IMPORT_C void Send(const TDesC8& aDesc, TRequestStatus& aStatus);IMPORT_C void CancelSend();IMPORT_C void Recv (TDes8& aDesc, TRequestStatus& aStatus);IMPORT_C void RecvOneOrMore( TDes8& aDesc, TRequestStatus& aStatus,TSockXfrLength& aLen );IMPORT_C void CancelRecv();IMPORT_C void CancelAll();IMPORT_C void CancelHandshake();IMPORT_C const CX509Certificate* ClientCert();IMPORT_C TInt SetClientCert(const CX509Certificate& aCert);IMPORT_C TClientCertMode ClientCertMode();IMPORT_C TInt SetClientCertMode(const TClientCertMode aClientCertMode);IMPORT_C const CX509Certificate* ServerCert();IMPORT_C TInt SetServerCert(const CX509Certificate& aCert);IMPORT_C TDialogMode DialogMode();IMPORT_C TInt SetDialogMode(const TDialogMode aDialogMode);IMPORT_C TInt AvailableCipherSuites(TDes8& aCiphers);IMPORT_C TInt SetAvailableCipherSuites(const TDesC8& aCiphers);IMPORT_C TInt CurrentCipherSuite(TDes8& aCipherSuite);USING THE NETWORK CONNECTIONIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_C187voidvoidTIntTIntvoidvoidTIntStartClientHandshake(TRequestStatus& aStatus);StartServerHandshake(TRequestStatus& aStatus);Protocol(TDes& aProtocol);SetProtocol(const TDesC& aProtocol);RenegotiateHandshake(TRequestStatus& aStatus);FlushSessionCache();GetOpt(TUint aOptionName, TUint aOptionLevel,TDes8& aOption);IMPORT_C TInt GetOpt(TUint aOptionName, TUint aOptionLevel,TInt& aOption);IMPORT_C TInt SetOpt(TUint aOptionName, TUint aOptionLevel,const TDesC8& aOption=TPtrC8(NULL,0));IMPORT_C TInt SetOpt(TUint aOptionName, TUint aOptionLevel,TInt aOption);};It should be noted that the Symbian OS TLS implementation currentlyonly supports client mode, i.e.

using the device as a client connecting toa remote server. Any CSecureSocket methods that require the deviceto act as a server for remote clients will return KErrNotSupported.These interfaces include SetServerCert() and StartServerHandshake().The handshakeThe first thing we need to do is create, open and connect an RSocket. TLScan be used to secure any connection-oriented socket. CSecureSocketrequires an already open and connected socket as input.RSocketServ iSockServ; // member variables of a active objectRSocket iSocket;TInetAddr iDstAddr;..._LIT(KTestAddress, "192.168.1.1");_LIT(KWwwTlsPort, 443);// port on which we’d expect to find// servers running TLS to offer HTTP// servicesUser::LeaveIfError(iSockServ.Connect());User::LeaveIfError(iSocket.Open(iSockServ, KAfInet, KSockStream,KProtocolInetTcp, iConnection));//Connect the socketiDstAddr.SetPort(KWwwTlsPort);iDstAddr.SetAddress(KTestAddress);User::LeaveIfError(iSocket.Connect(iDstAddr, iStatus));Next we can create the secure socket by calling CSecureSocket::NewL() and passing in the RSocket and secure protocol name.

Thesupported protocol names are ‘‘SSL3.0’’ or ‘‘TLS1.0’’ and can besupplied in upper or lower case.188IP AND RELATED TECHNOLOGIESThe function will return a pointer to the newly created CSecureSocket. The dialog mode and current cipher suites are set to thedefaults, which are Attended mode and {0x00,0x00} respectively.CSecureSocket* iSecureSocket; // class member..._LIT(KSSLProtocol,"tls1.0");iSecureSocket = CSecureSocket::NewL(iSocket, KSSLProtocol);We can optionally specify which cipher suites we want to use in thenegotiation.

We would need to call AvailableCipherSuites() toretrieve all the cipher suites supported by the device, then choose a subsetof cipher suites to use for the session. If a preference is not specified, theorder of the cipher suites will be the default based on the available ciphersuites.The list of cipher suites supplied to SetAvailableCipherSuites()must be in two-byte format, i.e., {0x00,0x25}. The order of the suites isimportant, they must be listed with the preferred suites first.The following cipher suites (in priority order) are supported by thecurrent implementation:PriorityCipher suiteValue1TLS− RSA− WITH− AES− 256− CBC− SHA{0x00,0x35}2TLS− RSA− WITH− AES− 128− CBC− SHA{0x00,0x2F}3TLS− RSA− WITH− 3DES− EDE− CBC− SHA{0x00,0x0A}4TLS− DHE− RSA− WITH− 3DES− EDE− CBC− SHA{0x00,0x16}5TLS− DHE− DSS− WITH− 3DES− EDE− CBC− SHA{0x00,0x13}6TLS− RSA− WITH− RC4− 128− SHA{0x00,0x05}7TLS− RSA− WITH− RC4− 128− MD5{0x00,0x04}8TLS− RSA− WITH− DES− CBC− SHA{0x00,0x09}9TLS− DHE− DSS− WITH− DES− CBC− SHA{0x00,0x12}10TLS− RSA− EXPORT− WITH− DES40− CBC− SHA{0x00,0x08}11TLS− RSA− EXPORT− WITH− RC4− 40− MD5{0x00,0x03}12TLS− DHE− DSS− EXPORT− WITH− DES40− CBC− SHA{0x00,0x11}13TLS− DHE− RSA− EXPORT− WITH− DES40− CBC− SHA{0x00,0x14}14TLS− DH− anon− EXPORT− WITH− DES40− CBC− SHA{0x00,0x19}USING THE NETWORK CONNECTION189Note, the following cipher suites are currently not supported:• Diffie–Hellman (static) cipher suites• Anonymous Diffie–Hellman• SSL v3.0 Fortezza cipher suites.const TUint KCipherSuiteSize = 2 ;TBuf8<KCipherSuiteSize> cipherSuite;cipherSuite.SetMax();cipherSuite[0] = 0x00;cipherSuite[1] = 0x03;// Set cipher suitesUser::LeaveIfError(iSecureSocket->SetAvailableCipherSuites(cipherSuite));Next, we need to set the domain name using:RBuf8 iHostName;// descriptor containing the name of the host to// which we connected (class member)...err = iSecureSocket.SetOpt(KSoSSLDomainName, KSolInetSSL, iHostName);To allow us to perform verification of the server certificate during thehandshake negotiation.

Характеристики

Тип файла
PDF-файл
Размер
3,18 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6358
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее