tests/auto/qudpsocket/tst_qudpsocket.cpp
changeset 0 1918ee327afb
child 3 41300fa6a67c
equal deleted inserted replaced
-1:000000000000 0:1918ee327afb
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the test suite of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 
       
    43 #include <QtTest/QtTest>
       
    44 
       
    45 #include <qcoreapplication.h>
       
    46 #include <qfileinfo.h>
       
    47 #include <qdatastream.h>
       
    48 #include <qudpsocket.h>
       
    49 #include <qhostaddress.h>
       
    50 #include <qhostinfo.h>
       
    51 #include <qmap.h>
       
    52 #ifdef TEST_QNETWORK_PROXY
       
    53 # include <QNetworkProxy>
       
    54 #endif
       
    55 
       
    56 
       
    57 #include <qstringlist.h>
       
    58 #include "../network-settings.h"
       
    59 
       
    60 Q_DECLARE_METATYPE(QHostAddress)
       
    61 
       
    62 //TESTED_CLASS=
       
    63 //TESTED_FILES=
       
    64 
       
    65 QT_FORWARD_DECLARE_CLASS(QUdpSocket)
       
    66 
       
    67 class tst_QUdpSocket : public QObject
       
    68 {
       
    69     Q_OBJECT
       
    70 
       
    71 public:
       
    72     tst_QUdpSocket();
       
    73     virtual ~tst_QUdpSocket();
       
    74 
       
    75 
       
    76 public slots:
       
    77     void initTestCase_data();
       
    78     void init();
       
    79     void cleanup();
       
    80 private slots:
       
    81     void constructing();
       
    82     void unconnectedServerAndClientTest();
       
    83     void broadcasting();
       
    84     void loop_data();
       
    85     void loop();
       
    86     void ipv6Loop_data();
       
    87     void ipv6Loop();
       
    88     void readLine();
       
    89     void pendingDatagramSize();
       
    90     void writeDatagram();
       
    91     void performance();
       
    92     void bindMode();
       
    93     void writeDatagramToNonExistingPeer_data();
       
    94     void writeDatagramToNonExistingPeer();
       
    95     void writeToNonExistingPeer_data();
       
    96     void writeToNonExistingPeer();
       
    97     void outOfProcessConnectedClientServerTest();
       
    98     void outOfProcessUnconnectedClientServerTest();
       
    99     void zeroLengthDatagram();
       
   100 
       
   101 protected slots:
       
   102     void empty_readyReadSlot();
       
   103     void empty_connectedSlot();
       
   104 };
       
   105 
       
   106 tst_QUdpSocket::tst_QUdpSocket()
       
   107 {
       
   108     Q_SET_DEFAULT_IAP
       
   109 }
       
   110 
       
   111 tst_QUdpSocket::~tst_QUdpSocket()
       
   112 {
       
   113 }
       
   114 
       
   115 void tst_QUdpSocket::initTestCase_data()
       
   116 {
       
   117     QTest::addColumn<bool>("setProxy");
       
   118     QTest::addColumn<int>("proxyType");
       
   119 
       
   120     QTest::newRow("WithoutProxy") << false << 0;
       
   121 #ifdef TEST_QNETWORK_PROXY
       
   122     QTest::newRow("WithSocks5Proxy") << true << int(QNetworkProxy::Socks5Proxy);
       
   123 #endif
       
   124 }
       
   125 
       
   126 void tst_QUdpSocket::init()
       
   127 {
       
   128     QFETCH_GLOBAL(bool, setProxy);
       
   129     if (setProxy) {
       
   130 #ifdef TEST_QNETWORK_PROXY
       
   131         QFETCH_GLOBAL(int, proxyType);
       
   132         if (proxyType == QNetworkProxy::Socks5Proxy) {
       
   133             QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080));
       
   134         }
       
   135 #endif
       
   136     }
       
   137 }
       
   138 
       
   139 void tst_QUdpSocket::cleanup()
       
   140 {
       
   141     QFETCH_GLOBAL(bool, setProxy);
       
   142     if (setProxy) {
       
   143 #ifdef TEST_QNETWORK_PROXY
       
   144         QNetworkProxy::setApplicationProxy(QNetworkProxy::DefaultProxy);
       
   145 #endif
       
   146     }
       
   147 }
       
   148 
       
   149 
       
   150 //----------------------------------------------------------------------------------
       
   151 
       
   152 void tst_QUdpSocket::constructing()
       
   153 {
       
   154     QUdpSocket socket;
       
   155 
       
   156     QVERIFY(socket.isSequential());
       
   157     QVERIFY(!socket.isOpen());
       
   158     QVERIFY(socket.socketType() == QUdpSocket::UdpSocket);
       
   159     QCOMPARE((int) socket.bytesAvailable(), 0);
       
   160     QCOMPARE(socket.canReadLine(), false);
       
   161     QCOMPARE(socket.readLine(), QByteArray());
       
   162     QCOMPARE(socket.socketDescriptor(), -1);
       
   163     QCOMPARE(socket.error(), QUdpSocket::UnknownSocketError);
       
   164     QCOMPARE(socket.errorString(), QString("Unknown error"));
       
   165 
       
   166     // Check the state of the socket api
       
   167 }
       
   168 
       
   169 void tst_QUdpSocket::unconnectedServerAndClientTest()
       
   170 {
       
   171     QUdpSocket serverSocket;
       
   172 
       
   173     qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
       
   174 
       
   175     QSignalSpy stateChangedSpy(&serverSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
       
   176     QVERIFY2(serverSocket.bind(), serverSocket.errorString().toLatin1().constData());
       
   177     QCOMPARE(stateChangedSpy.count(), 1);
       
   178 
       
   179     const char *message[] = {"Yo mista", "Yo", "Wassap"};
       
   180 
       
   181     QHostAddress serverAddress = QHostAddress::LocalHost;
       
   182     if (!(serverSocket.localAddress() == QHostAddress::Any))
       
   183         serverAddress = serverSocket.localAddress();
       
   184 
       
   185     for (int i = 0; i < 3; ++i) {
       
   186         QUdpSocket clientSocket;
       
   187         QCOMPARE(int(clientSocket.writeDatagram(message[i], strlen(message[i]),
       
   188                                                serverAddress, serverSocket.localPort())),
       
   189                 int(strlen(message[i])));
       
   190         char buf[1024];
       
   191         QHostAddress host;
       
   192         quint16 port;
       
   193         QVERIFY(serverSocket.waitForReadyRead(5000));
       
   194         QCOMPARE(int(serverSocket.readDatagram(buf, sizeof(buf), &host, &port)),
       
   195                 int(strlen(message[i])));
       
   196         buf[strlen(message[i])] = '\0';
       
   197         QCOMPARE(QByteArray(buf), QByteArray(message[i]));
       
   198     }
       
   199 }
       
   200 
       
   201 //----------------------------------------------------------------------------------
       
   202 
       
   203 void tst_QUdpSocket::broadcasting()
       
   204 {
       
   205     QFETCH_GLOBAL(bool, setProxy);
       
   206     if (setProxy) {
       
   207 #ifdef TEST_QNETWORK_PROXY
       
   208         QFETCH_GLOBAL(int, proxyType);
       
   209         if (proxyType == QNetworkProxy::Socks5Proxy) {
       
   210             QSKIP("With socks5 Broadcast is not supported.", SkipSingle);
       
   211         }
       
   212 #endif
       
   213     }
       
   214 #ifdef Q_OS_AIX
       
   215     QSKIP("Broadcast does not work on darko", SkipAll);
       
   216 #endif
       
   217     const char *message[] = {"Yo mista", "", "Yo", "Wassap"};
       
   218 
       
   219     for (int i = 0; i < 4; ++i) {
       
   220         QUdpSocket serverSocket;
       
   221         QVERIFY2(serverSocket.bind(QHostAddress::Any, 5000), serverSocket.errorString().toLatin1().constData());
       
   222 
       
   223         QCOMPARE(serverSocket.state(), QUdpSocket::BoundState);
       
   224 
       
   225         connect(&serverSocket, SIGNAL(readyRead()), SLOT(empty_readyReadSlot()));
       
   226 
       
   227         QUdpSocket broadcastSocket;
       
   228 
       
   229         for (int j = 0; j < 100; ++j) {
       
   230             broadcastSocket.writeDatagram(message[i], strlen(message[i]),
       
   231                 QHostAddress::Broadcast, 5000);
       
   232             QTestEventLoop::instance().enterLoop(15);
       
   233             if (QTestEventLoop::instance().timeout()) {
       
   234 #if defined(Q_OS_FREEBSD)
       
   235                 QEXPECT_FAIL("",
       
   236                              "Broadcasting to 255.255.255.255 does not work on FreeBSD",
       
   237                              Abort);
       
   238                 QVERIFY(false); // seems that QFAIL() doesn't respect the QEXPECT_FAIL() :/
       
   239 #endif
       
   240                 QFAIL("Network operation timed out");
       
   241             }
       
   242             QVERIFY(serverSocket.hasPendingDatagrams());
       
   243 
       
   244             do {
       
   245                 QByteArray arr; arr.resize(serverSocket.pendingDatagramSize() + 1);
       
   246                 QHostAddress host;
       
   247                 quint16 port;
       
   248                 QCOMPARE((int) serverSocket.readDatagram(arr.data(), arr.size() - 1, &host, &port),
       
   249                     (int) strlen(message[i]));
       
   250                 arr.resize(strlen(message[i]));
       
   251                 QCOMPARE(arr, QByteArray(message[i]));
       
   252             } while (serverSocket.hasPendingDatagrams());
       
   253         }
       
   254     }
       
   255 }
       
   256 
       
   257 //----------------------------------------------------------------------------------
       
   258 
       
   259 void tst_QUdpSocket::loop_data()
       
   260 {
       
   261     QTest::addColumn<QByteArray>("peterMessage");
       
   262     QTest::addColumn<QByteArray>("paulMessage");
       
   263     QTest::addColumn<bool>("success");
       
   264 
       
   265     QTest::newRow("\"Almond!\" | \"Joy!\"") << QByteArray("Almond!") << QByteArray("Joy!") << true;
       
   266     QTest::newRow("\"A\" | \"B\"") << QByteArray("A") << QByteArray("B") << true;
       
   267     QTest::newRow("\"AB\" | \"B\"") << QByteArray("AB") << QByteArray("B") << true;
       
   268     QTest::newRow("\"AB\" | \"BB\"") << QByteArray("AB") << QByteArray("BB") << true;
       
   269     QTest::newRow("\"A\\0B\" | \"B\\0B\"") << QByteArray::fromRawData("A\0B", 3) << QByteArray::fromRawData("B\0B", 3) << true;
       
   270     QTest::newRow("\"(nil)\" | \"(nil)\"") << QByteArray() << QByteArray() << true;
       
   271     QTest::newRow("Bigmessage") << QByteArray(600, '@') << QByteArray(600, '@') << true;
       
   272 }
       
   273 
       
   274 void tst_QUdpSocket::loop()
       
   275 {
       
   276     QFETCH(QByteArray, peterMessage);
       
   277     QFETCH(QByteArray, paulMessage);
       
   278     QFETCH(bool, success);
       
   279 
       
   280     QUdpSocket peter;
       
   281     QUdpSocket paul;
       
   282 
       
   283     QVERIFY2(peter.bind(), peter.errorString().toLatin1().constData());
       
   284     QVERIFY2(paul.bind(), paul.errorString().toLatin1().constData());
       
   285 
       
   286     QHostAddress peterAddress = QHostAddress::LocalHost;
       
   287     if (!(peter.localAddress() == QHostAddress::Any))
       
   288         peterAddress = peter.localAddress();
       
   289     QHostAddress pualAddress = QHostAddress::LocalHost;
       
   290     if (!(paul.localAddress() == QHostAddress::Any))
       
   291         pualAddress = paul.localAddress();
       
   292 
       
   293     QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(),
       
   294                                 pualAddress, paul.localPort()), qint64(peterMessage.length()));
       
   295     QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
       
   296                                peterAddress, peter.localPort()), qint64(paulMessage.length()));
       
   297 
       
   298     QVERIFY(peter.waitForReadyRead(5000));
       
   299     QVERIFY(paul.waitForReadyRead(5000));
       
   300     char peterBuffer[16*1024];
       
   301     char paulBuffer[16*1024];
       
   302     if (success) {
       
   303         QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
       
   304         QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
       
   305     } else {
       
   306         QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
       
   307         QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
       
   308     }
       
   309 
       
   310     QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
       
   311     QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
       
   312 }
       
   313 
       
   314 //----------------------------------------------------------------------------------
       
   315 
       
   316 void tst_QUdpSocket::ipv6Loop_data()
       
   317 {
       
   318     loop_data();
       
   319 }
       
   320 
       
   321 void tst_QUdpSocket::ipv6Loop()
       
   322 {
       
   323 #if defined(Q_OS_SYMBIAN)
       
   324     QSKIP("Symbian IPv6 is not yet supported", SkipAll);
       
   325 #endif
       
   326     QFETCH(QByteArray, peterMessage);
       
   327     QFETCH(QByteArray, paulMessage);
       
   328     QFETCH(bool, success);
       
   329 
       
   330     QUdpSocket peter;
       
   331     QUdpSocket paul;
       
   332 
       
   333     quint16 peterPort = 28124;
       
   334     quint16 paulPort = 28123;
       
   335 
       
   336     if (!peter.bind(QHostAddress::LocalHostIPv6, peterPort)) {
       
   337     QCOMPARE(peter.error(), QUdpSocket::UnsupportedSocketOperationError);
       
   338     } else {
       
   339     QVERIFY(paul.bind(QHostAddress::LocalHostIPv6, paulPort));
       
   340 
       
   341     QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(), QHostAddress("::1"),
       
   342                                     paulPort), qint64(peterMessage.length()));
       
   343     QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
       
   344                                    QHostAddress("::1"), peterPort), qint64(paulMessage.length()));
       
   345 
       
   346     char peterBuffer[16*1024];
       
   347     char paulBuffer[16*1024];
       
   348 #if !defined(Q_OS_WINCE)
       
   349         QVERIFY(peter.waitForReadyRead(5000));
       
   350         QVERIFY(paul.waitForReadyRead(5000));
       
   351 #else
       
   352         QVERIFY(peter.waitForReadyRead(15000));
       
   353         QVERIFY(paul.waitForReadyRead(15000));
       
   354 #endif
       
   355     if (success) {
       
   356         QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
       
   357         QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
       
   358     } else {
       
   359         QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
       
   360         QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
       
   361     }
       
   362 
       
   363     QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
       
   364     QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
       
   365     }
       
   366 }
       
   367 
       
   368 void tst_QUdpSocket::empty_readyReadSlot()
       
   369 {
       
   370     QTestEventLoop::instance().exitLoop();
       
   371 }
       
   372 
       
   373 void tst_QUdpSocket::empty_connectedSlot()
       
   374 {
       
   375     QTestEventLoop::instance().exitLoop();
       
   376 }
       
   377 
       
   378 //----------------------------------------------------------------------------------
       
   379 
       
   380 void tst_QUdpSocket::readLine()
       
   381 {
       
   382     QUdpSocket socket1;
       
   383     QVERIFY2(socket1.bind(), socket1.errorString().toLatin1().constData());
       
   384 
       
   385     QUdpSocket socket2;
       
   386     socket2.connectToHost("127.0.0.1", socket1.localPort());
       
   387     QVERIFY(socket2.waitForConnected(5000));
       
   388 }
       
   389 
       
   390 //----------------------------------------------------------------------------------
       
   391 
       
   392 void tst_QUdpSocket::pendingDatagramSize()
       
   393 {
       
   394     QUdpSocket server;
       
   395     QVERIFY2(server.bind(), server.errorString().toLatin1().constData());
       
   396 
       
   397     QHostAddress serverAddress = QHostAddress::LocalHost;
       
   398     if (!(server.localAddress() == QHostAddress::Any))
       
   399         serverAddress = server.localAddress();
       
   400 
       
   401     QUdpSocket client;
       
   402     QVERIFY(client.writeDatagram("this is", 7, serverAddress, server.localPort()) == 7);
       
   403     QVERIFY(client.writeDatagram(0, 0, serverAddress, server.localPort()) == 0);
       
   404     QVERIFY(client.writeDatagram("3 messages", 10, serverAddress, server.localPort()) == 10);
       
   405 
       
   406     char c = 0;
       
   407     QVERIFY(server.waitForReadyRead());
       
   408     if (server.hasPendingDatagrams()) {
       
   409 #if defined Q_OS_HPUX && defined __ia64
       
   410         QEXPECT_FAIL("", "HP-UX 11i v2 can't determine the datagram size correctly.", Abort);
       
   411 #endif
       
   412         QCOMPARE(server.pendingDatagramSize(), qint64(7));
       
   413         c = '\0';
       
   414         QCOMPARE(server.readDatagram(&c, 1), qint64(1));
       
   415         QCOMPARE(c, 't');
       
   416         c = '\0';
       
   417     } else {
       
   418         QSKIP("does not have the 1st datagram", SkipSingle);
       
   419     }
       
   420 
       
   421     if (server.hasPendingDatagrams()) {
       
   422         QCOMPARE(server.pendingDatagramSize(), qint64(0));
       
   423         QCOMPARE(server.readDatagram(&c, 1), qint64(0));
       
   424         QCOMPARE(c, '\0'); // untouched
       
   425     c = '\0';
       
   426     } else {
       
   427         QSKIP("does not have the 2nd datagram", SkipSingle);
       
   428     }
       
   429 
       
   430     if (server.hasPendingDatagrams()) {
       
   431         QCOMPARE(server.pendingDatagramSize(), qint64(10));
       
   432         QCOMPARE(server.readDatagram(&c, 1), qint64(1));
       
   433         QCOMPARE(c, '3');
       
   434     } else {
       
   435         QSKIP("does not have the 3rd datagram", SkipSingle);
       
   436     }
       
   437 }
       
   438 
       
   439 
       
   440 void tst_QUdpSocket::writeDatagram()
       
   441 {
       
   442     QUdpSocket server;
       
   443     QVERIFY2(server.bind(), server.errorString().toLatin1().constData());
       
   444 
       
   445     QHostAddress serverAddress = QHostAddress::LocalHost;
       
   446     if (!(server.localAddress() == QHostAddress::Any))
       
   447         serverAddress = server.localAddress();
       
   448 
       
   449     QUdpSocket client;
       
   450 
       
   451     qRegisterMetaType<qint64>("qint64");
       
   452     qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
       
   453 
       
   454     for(int i=0;;i++) {
       
   455         QSignalSpy errorspy(&client, SIGNAL(error(QAbstractSocket::SocketError)));
       
   456         QSignalSpy bytesspy(&client, SIGNAL(bytesWritten(qint64)));
       
   457 
       
   458         qint64 written = client.writeDatagram(QByteArray(i * 1024, 'w'), serverAddress,
       
   459                                                   server.localPort());
       
   460 
       
   461         if (written != i * 1024) {
       
   462 #if defined (Q_OS_HPUX)
       
   463             QSKIP("HP-UX 11.11 on hai (PA-RISC 64) truncates too long datagrams.", SkipSingle);
       
   464 #endif
       
   465             QCOMPARE(bytesspy.count(), 0);
       
   466             QCOMPARE(errorspy.count(), 1);
       
   467             QCOMPARE(*static_cast<const int *>(errorspy.at(0).at(0).constData()),
       
   468                     int(QUdpSocket::DatagramTooLargeError));
       
   469             QCOMPARE(client.error(), QUdpSocket::DatagramTooLargeError);
       
   470             break;
       
   471         }
       
   472         QVERIFY(bytesspy.count() == 1);
       
   473         QCOMPARE(*static_cast<const qint64 *>(bytesspy.at(0).at(0).constData()),
       
   474                 qint64(i * 1024));
       
   475         QCOMPARE(errorspy.count(), 0);
       
   476         if (!server.waitForReadyRead(5000))
       
   477             QSKIP(QString("UDP packet lost at size %1, unable to complete the test.").arg(i * 1024).toLatin1().data(), SkipSingle);
       
   478         QCOMPARE(server.pendingDatagramSize(), qint64(i * 1024));
       
   479         QCOMPARE(server.readDatagram(0, 0), qint64(0));
       
   480     }
       
   481 }
       
   482 
       
   483 void tst_QUdpSocket::performance()
       
   484 {
       
   485 #if defined(Q_OS_SYMBIAN)
       
   486     // Large packets seems not to go through on Symbian
       
   487     // Reason might be also fragmentation due to VPN connection etc
       
   488 
       
   489     QFETCH_GLOBAL(bool, setProxy);
       
   490     QFETCH_GLOBAL(int, proxyType);
       
   491 
       
   492     int arrSize = 8192;
       
   493     if (setProxy && proxyType == QNetworkProxy::Socks5Proxy)
       
   494         arrSize = 1024;
       
   495 
       
   496     QByteArray arr(arrSize, '@');
       
   497 #else
       
   498     QByteArray arr(8192, '@');
       
   499 #endif // Q_OS_SYMBIAN
       
   500 
       
   501     QUdpSocket server;
       
   502     QVERIFY2(server.bind(), server.errorString().toLatin1().constData());
       
   503 
       
   504     QHostAddress serverAddress = QHostAddress::LocalHost;
       
   505     if (!(server.localAddress() == QHostAddress::Any))
       
   506         serverAddress = server.localAddress();
       
   507 
       
   508     QUdpSocket client;
       
   509     client.connectToHost(serverAddress, server.localPort());
       
   510 
       
   511     QTime stopWatch;
       
   512     stopWatch.start();
       
   513 
       
   514     qint64 nbytes = 0;
       
   515     while (stopWatch.elapsed() < 5000) {
       
   516         for (int i = 0; i < 100; ++i) {
       
   517             if (client.write(arr.data(), arr.size()) > 0) {
       
   518                 do {
       
   519                     nbytes += server.readDatagram(arr.data(), arr.size());
       
   520                 } while (server.hasPendingDatagrams());
       
   521             }
       
   522         }
       
   523     }
       
   524 
       
   525     float secs = stopWatch.elapsed() / 1000.0;
       
   526     qDebug("\t%.2fMB/%.2fs: %.2fMB/s", float(nbytes / (1024.0*1024.0)),
       
   527            secs, float(nbytes / (1024.0*1024.0)) / secs);
       
   528 
       
   529 #if defined(Q_OS_SYMBIAN)
       
   530     if(nbytes == 0) {
       
   531         qDebug("No bytes passed through local UDP socket, since UDP socket write returns EWOULDBLOCK");
       
   532         qDebug("Should try with blocking sockets, but it is not currently possible due to Open C defect");
       
   533     }
       
   534 #endif
       
   535 
       
   536 }
       
   537 
       
   538 void tst_QUdpSocket::bindMode()
       
   539 {
       
   540     QFETCH_GLOBAL(bool, setProxy);
       
   541     if (setProxy) {
       
   542 #ifdef TEST_QNETWORK_PROXY
       
   543         QFETCH_GLOBAL(int, proxyType);
       
   544         if (proxyType == QNetworkProxy::Socks5Proxy) {
       
   545             QSKIP("With socks5 explicit port binding is not supported.", SkipAll);
       
   546         }
       
   547 #endif
       
   548     }
       
   549 
       
   550     QUdpSocket socket;
       
   551     QVERIFY2(socket.bind(), socket.errorString().toLatin1().constData());
       
   552     QUdpSocket socket2;
       
   553     QVERIFY(!socket2.bind(socket.localPort()));
       
   554 #if defined(Q_OS_SYMBIAN)
       
   555     if(RProcess().HasCapability(ECapabilityNetworkControl)) {
       
   556         qDebug("Test executed *with* NetworkControl capability");
       
   557         // In Symbian OS ReuseAddressHint together with NetworkControl capability
       
   558         // gives application *always* right to bind to port. I.e. it does not matter
       
   559         // if first socket was bound with any bind flag. Since autotests in Symbian
       
   560         // are currently executed with ALL -TCB rights, this path is the one executed.
       
   561         QVERIFY(socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
       
   562         socket.close();
       
   563         socket2.close();
       
   564 
       
   565         QVERIFY2(socket.bind(0, QUdpSocket::ShareAddress), socket.errorString().toLatin1().constData());
       
   566         QVERIFY(!socket2.bind(socket.localPort()));
       
   567         QVERIFY2(socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint), socket2.errorString().toLatin1().constData());
       
   568         socket.close();
       
   569         socket2.close();
       
   570 
       
   571         QVERIFY2(socket.bind(0, QUdpSocket::DontShareAddress), socket.errorString().toLatin1().constData());
       
   572         QVERIFY(!socket2.bind(socket.localPort()));
       
   573         QVERIFY(socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
       
   574         socket.close();
       
   575         socket2.close();
       
   576     } else {
       
   577         qDebug("Test executed *without* NetworkControl capability");
       
   578         // If we don't have NetworkControl capability, attempt to bind already bound
       
   579         // address will *always* fail. I.e. it does not matter if first socket was
       
   580         // bound with any bind flag.
       
   581         QVERIFY(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
       
   582         socket.close();
       
   583 
       
   584         QVERIFY2(socket.bind(0, QUdpSocket::ShareAddress), socket.errorString().toLatin1().constData());
       
   585         QVERIFY(!socket2.bind(socket.localPort()));
       
   586         QVERIFY2(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint), socket2.errorString().toLatin1().constData());
       
   587         socket.close();
       
   588 
       
   589         QVERIFY2(socket.bind(0, QUdpSocket::DontShareAddress), socket.errorString().toLatin1().constData());
       
   590         QVERIFY(!socket2.bind(socket.localPort()));
       
   591         QVERIFY(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
       
   592         socket.close();
       
   593     }
       
   594 #elif defined(Q_OS_UNIX)
       
   595     QVERIFY(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
       
   596     socket.close();
       
   597     QVERIFY2(socket.bind(0, QUdpSocket::ShareAddress), socket.errorString().toLatin1().constData());
       
   598     QVERIFY2(socket2.bind(socket.localPort()), socket2.errorString().toLatin1().constData());
       
   599     socket2.close();
       
   600     QVERIFY2(socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint), socket2.errorString().toLatin1().constData());
       
   601 #else
       
   602 
       
   603     // Depending on the user's privileges, this or will succeed or
       
   604     // fail. Admins are allowed to reuse the address, but nobody else.
       
   605     if (!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint), socket2.errorString().toLatin1().constData())
       
   606         qWarning("Failed to bind with QUdpSocket::ReuseAddressHint, user isn't an adminstrator?");
       
   607     socket.close();
       
   608     QVERIFY2(socket.bind(0, QUdpSocket::ShareAddress), socket.errorString().toLatin1().constData());
       
   609     QVERIFY(!socket2.bind(socket.localPort()));
       
   610     socket.close();
       
   611     QVERIFY2(socket.bind(0, QUdpSocket::DontShareAddress), socket.errorString().toLatin1().constData());
       
   612     QVERIFY(!socket2.bind(socket.localPort()));
       
   613     QVERIFY(!socket2.bind(socket.localPort(), QUdpSocket::ReuseAddressHint));
       
   614 #endif
       
   615 }
       
   616 
       
   617 void tst_QUdpSocket::writeDatagramToNonExistingPeer_data()
       
   618 {
       
   619     QTest::addColumn<bool>("bind");
       
   620     QTest::addColumn<QHostAddress>("peerAddress");
       
   621     QHostAddress localhost(QHostAddress::LocalHost);
       
   622 #if !defined(Q_OS_SYMBIAN)
       
   623     QHostAddress remote = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first();
       
   624 #endif
       
   625 
       
   626     QTest::newRow("localhost-unbound") << false << localhost;
       
   627     QTest::newRow("localhost-bound") << true << localhost;
       
   628 #if !defined(Q_OS_SYMBIAN)
       
   629     QTest::newRow("remote-unbound") << false << remote;
       
   630     QTest::newRow("remote-bound") << true << remote;
       
   631 #endif
       
   632 }
       
   633 
       
   634 void tst_QUdpSocket::writeDatagramToNonExistingPeer()
       
   635 {
       
   636     QFETCH(bool, bind);
       
   637     QFETCH(QHostAddress, peerAddress);
       
   638 
       
   639     quint16 peerPort = 33533 + int(bind);
       
   640 
       
   641     QUdpSocket sUdp;
       
   642     QSignalSpy sReadyReadSpy(&sUdp, SIGNAL(readyRead()));
       
   643     if (bind)
       
   644         QVERIFY(sUdp.bind());
       
   645     QCOMPARE(sUdp.writeDatagram("", 1, peerAddress, peerPort), qint64(1));
       
   646     QTestEventLoop::instance().enterLoop(1);
       
   647     QCOMPARE(sReadyReadSpy.count(), 0);
       
   648 }
       
   649 
       
   650 void tst_QUdpSocket::writeToNonExistingPeer_data()
       
   651 {
       
   652     QTest::addColumn<QHostAddress>("peerAddress");
       
   653     QHostAddress localhost(QHostAddress::LocalHost);
       
   654 #if !defined(Q_OS_SYMBIAN)
       
   655     QHostAddress remote = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first();
       
   656 #endif
       
   657     // write (required to be connected)
       
   658     QTest::newRow("localhost") << localhost;
       
   659 #if !defined(Q_OS_SYMBIAN)
       
   660     QTest::newRow("remote") << remote;
       
   661 #endif
       
   662 }
       
   663 
       
   664 void tst_QUdpSocket::writeToNonExistingPeer()
       
   665 {
       
   666     QSKIP("Connected-mode UDP sockets and their behaviour are erratic", SkipAll);
       
   667     QFETCH(QHostAddress, peerAddress);
       
   668     quint16 peerPort = 34534;
       
   669     qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
       
   670 
       
   671     QUdpSocket sConnected;
       
   672     QSignalSpy sConnectedReadyReadSpy(&sConnected, SIGNAL(readyRead()));
       
   673     QSignalSpy sConnectedErrorSpy(&sConnected, SIGNAL(error(QAbstractSocket::SocketError)));
       
   674     sConnected.connectToHost(peerAddress, peerPort, QIODevice::ReadWrite);
       
   675 
       
   676     // the first write succeeds...
       
   677     QCOMPARE(sConnected.write("", 1), qint64(1));
       
   678 
       
   679     // the second one should fail!
       
   680     QTest::qSleep(1000);                   // do not process events
       
   681     QCOMPARE(sConnected.write("", 1), qint64(-1));
       
   682     QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
       
   683 
       
   684     // the third one will succeed...
       
   685     QCOMPARE(sConnected.write("", 1), qint64(1));
       
   686     QTestEventLoop::instance().enterLoop(1);
       
   687     QCOMPARE(sConnectedReadyReadSpy.count(), 0);
       
   688     QCOMPARE(sConnectedErrorSpy.count(), 1);
       
   689     QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
       
   690 
       
   691     // we should now get a read error
       
   692     QCOMPARE(sConnected.write("", 1), qint64(1));
       
   693     QTest::qSleep(1000);                   // do not process events
       
   694     char buf[2];
       
   695     QVERIFY(!sConnected.hasPendingDatagrams());
       
   696     QCOMPARE(sConnected.bytesAvailable(), Q_INT64_C(0));
       
   697     QCOMPARE(sConnected.pendingDatagramSize(), Q_INT64_C(-1));
       
   698     QCOMPARE(sConnected.readDatagram(buf, 2), Q_INT64_C(-1));
       
   699     QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
       
   700 
       
   701     QCOMPARE(sConnected.write("", 1), qint64(1));
       
   702     QTest::qSleep(1000);                   // do not process events
       
   703     QCOMPARE(sConnected.read(buf, 2), Q_INT64_C(0));
       
   704     QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
       
   705 
       
   706     // we should still be connected
       
   707     QCOMPARE(int(sConnected.state()), int(QUdpSocket::ConnectedState));
       
   708 }
       
   709 
       
   710 void tst_QUdpSocket::outOfProcessConnectedClientServerTest()
       
   711 {
       
   712 #if defined(Q_OS_WINCE) || defined (Q_OS_SYMBIAN)
       
   713     QSKIP("This test depends on reading data from QProcess (not supported on Qt/WinCE and Symbian).", SkipAll);
       
   714 #endif
       
   715 #if defined(QT_NO_PROCESS)
       
   716     QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll);
       
   717 #else
       
   718 
       
   719     QProcess serverProcess;
       
   720     serverProcess.start(QLatin1String("clientserver/clientserver server 1 1"),
       
   721                         QIODevice::ReadWrite | QIODevice::Text);
       
   722 
       
   723     // Wait until the server has started and reports success.
       
   724     while (!serverProcess.canReadLine())
       
   725         QVERIFY(serverProcess.waitForReadyRead(3000));
       
   726     QByteArray serverGreeting = serverProcess.readLine();
       
   727     QVERIFY(serverGreeting != QByteArray("XXX\n"));
       
   728     int serverPort = serverGreeting.trimmed().toInt();
       
   729     QVERIFY(serverPort > 0 && serverPort < 65536);
       
   730 
       
   731     QProcess clientProcess;
       
   732     clientProcess.start(QString::fromLatin1("clientserver/clientserver connectedclient %1 %2")
       
   733                         .arg(QLatin1String("127.0.0.1")).arg(serverPort),
       
   734                         QIODevice::ReadWrite | QIODevice::Text);
       
   735     // Wait until the server has started and reports success.
       
   736     while (!clientProcess.canReadLine())
       
   737         QVERIFY(clientProcess.waitForReadyRead(3000));
       
   738     QByteArray clientGreeting = clientProcess.readLine();
       
   739     QCOMPARE(clientGreeting, QByteArray("ok\n"));
       
   740 
       
   741     // Let the client and server talk for 3 seconds
       
   742     QTest::qWait(3000);
       
   743 
       
   744     QStringList serverData = QString::fromLocal8Bit(serverProcess.readAll()).split("\n");
       
   745     QStringList clientData = QString::fromLocal8Bit(clientProcess.readAll()).split("\n");
       
   746     QVERIFY(serverData.size() > 5);
       
   747     QVERIFY(clientData.size() > 5);
       
   748 
       
   749     for (int i = 0; i < clientData.size() / 2; ++i) {
       
   750         QCOMPARE(clientData.at(i * 2), QString("readData()"));
       
   751         QCOMPARE(serverData.at(i * 3), QString("readData()"));
       
   752 
       
   753         QString cdata = clientData.at(i * 2 + 1);
       
   754         QString sdata = serverData.at(i * 3 + 1);
       
   755         QVERIFY(cdata.startsWith(QLatin1String("got ")));
       
   756 
       
   757         QCOMPARE(cdata.mid(4).trimmed().toInt(), sdata.mid(4).trimmed().toInt() * 2);
       
   758         QVERIFY(serverData.at(i * 3 + 2).startsWith(QLatin1String("sending ")));
       
   759         QCOMPARE(serverData.at(i * 3 + 2).trimmed().mid(8).toInt(),
       
   760                  sdata.mid(4).trimmed().toInt() * 2);
       
   761     }
       
   762 
       
   763     clientProcess.kill();
       
   764     QVERIFY(clientProcess.waitForFinished());
       
   765     serverProcess.kill();
       
   766     QVERIFY(serverProcess.waitForFinished());
       
   767 #endif
       
   768 }
       
   769 
       
   770 void tst_QUdpSocket::outOfProcessUnconnectedClientServerTest()
       
   771 {
       
   772 #if defined(Q_OS_WINCE) || defined (Q_OS_SYMBIAN)
       
   773     QSKIP("This test depends on reading data from QProcess (not supported on Qt/WinCE and Symbian).", SkipAll);
       
   774 #endif
       
   775 #if defined(QT_NO_PROCESS)
       
   776     QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll);
       
   777 #else
       
   778 
       
   779     QProcess serverProcess;
       
   780     serverProcess.start(QLatin1String("clientserver/clientserver server 1 1"),
       
   781                         QIODevice::ReadWrite | QIODevice::Text);
       
   782 
       
   783     // Wait until the server has started and reports success.
       
   784     while (!serverProcess.canReadLine())
       
   785         QVERIFY(serverProcess.waitForReadyRead(3000));
       
   786     QByteArray serverGreeting = serverProcess.readLine();
       
   787     QVERIFY(serverGreeting != QByteArray("XXX\n"));
       
   788     int serverPort = serverGreeting.trimmed().toInt();
       
   789     QVERIFY(serverPort > 0 && serverPort < 65536);
       
   790 
       
   791     QProcess clientProcess;
       
   792     clientProcess.start(QString::fromLatin1("clientserver/clientserver unconnectedclient %1 %2")
       
   793                         .arg(QLatin1String("127.0.0.1")).arg(serverPort),
       
   794                         QIODevice::ReadWrite | QIODevice::Text);
       
   795     // Wait until the server has started and reports success.
       
   796     while (!clientProcess.canReadLine())
       
   797         QVERIFY(clientProcess.waitForReadyRead(3000));
       
   798     QByteArray clientGreeting = clientProcess.readLine();
       
   799     QCOMPARE(clientGreeting, QByteArray("ok\n"));
       
   800 
       
   801     // Let the client and server talk for 3 seconds
       
   802     QTest::qWait(3000);
       
   803 
       
   804     QStringList serverData = QString::fromLocal8Bit(serverProcess.readAll()).split("\n");
       
   805     QStringList clientData = QString::fromLocal8Bit(clientProcess.readAll()).split("\n");
       
   806 
       
   807     QVERIFY(serverData.size() > 5);
       
   808     QVERIFY(clientData.size() > 5);
       
   809 
       
   810     for (int i = 0; i < clientData.size() / 2; ++i) {
       
   811         QCOMPARE(clientData.at(i * 2), QString("readData()"));
       
   812         QCOMPARE(serverData.at(i * 3), QString("readData()"));
       
   813 
       
   814         QString cdata = clientData.at(i * 2 + 1);
       
   815         QString sdata = serverData.at(i * 3 + 1);
       
   816         QVERIFY(cdata.startsWith(QLatin1String("got ")));
       
   817 
       
   818         QCOMPARE(cdata.mid(4).trimmed().toInt(), sdata.mid(4).trimmed().toInt() * 2);
       
   819         QVERIFY(serverData.at(i * 3 + 2).startsWith(QLatin1String("sending ")));
       
   820         QCOMPARE(serverData.at(i * 3 + 2).trimmed().mid(8).toInt(),
       
   821                  sdata.mid(4).trimmed().toInt() * 2);
       
   822     }
       
   823 
       
   824     clientProcess.kill();
       
   825     QVERIFY(clientProcess.waitForFinished());
       
   826     serverProcess.kill();
       
   827     QVERIFY(serverProcess.waitForFinished());
       
   828 #endif
       
   829 }
       
   830 
       
   831 void tst_QUdpSocket::zeroLengthDatagram()
       
   832 {
       
   833     QFETCH_GLOBAL(bool, setProxy);
       
   834     if (setProxy)
       
   835         return;
       
   836 
       
   837     QUdpSocket receiver;
       
   838     QVERIFY(receiver.bind());
       
   839 
       
   840     QVERIFY(!receiver.waitForReadyRead(100));
       
   841     QVERIFY(!receiver.hasPendingDatagrams());
       
   842 
       
   843     QUdpSocket sender;
       
   844     QCOMPARE(sender.writeDatagram(QByteArray(), QHostAddress::LocalHost, receiver.localPort()), qint64(0));
       
   845 
       
   846     QVERIFY(receiver.waitForReadyRead(1000));
       
   847     QVERIFY(receiver.hasPendingDatagrams());
       
   848 
       
   849     char buf;
       
   850     QCOMPARE(receiver.readDatagram(&buf, 1), qint64(0));
       
   851 }
       
   852 
       
   853 QTEST_MAIN(tst_QUdpSocket)
       
   854 #include "tst_qudpsocket.moc"