1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 //#define QNATIVESOCKETENGINE_DEBUG
44 /*! \class QNativeSocketEngine
47 \brief The QNativeSocketEngine class provides low level access to a socket.
53 QtSocketLayer provides basic socket functionality provided by the
54 operating system. It also keeps track of what state the socket is
55 in, and which errors that occur.
57 The classes QTcpSocket, QUdpSocket and QTcpServer provide a
58 higher level API, and are in general more useful for the common
61 There are two main ways of initializing the a QNativeSocketEngine; either
62 create a new socket by passing the socket type (TcpSocket or
63 UdpSocket) and network layer protocol (IPv4Protocol or
64 IPv6Protocol) to initialize(), or pass an existing socket
65 descriptor and have QNativeSocketEngine determine the type and protocol
66 itself. The native socket descriptor can later be fetched by
67 calling socketDescriptor(). The socket is made non-blocking, but
68 blocking behavior can still be achieved by calling waitForRead()
69 and waitForWrite(). isValid() can be called to check if the socket
70 has been successfully initialized and is ready to use.
72 To connect to a host, determine its address and pass this and the
73 port number to connectToHost(). The socket can then be used as a
74 TCP or UDP client. Otherwise; bind(), listen() and accept() are
75 used to have the socket function as a TCP or UDP server. Call
76 close() to close the socket.
78 bytesAvailable() is called to determine how much data is available
79 for reading. read() and write() are used by both TCP and UDP
80 clients to exchange data with the connected peer. UDP clients can
81 also call hasMoreDatagrams(), nextDatagramSize(),
82 readDatagram(), and writeDatagram().
84 Call state() to determine the state of the socket, for
85 example, ListeningState or ConnectedState. socketType() tells
86 whether the socket is a TCP socket or a UDP socket, or if the
87 socket type is unknown. protocol() is used to determine the
88 socket's network layer protocol.
90 localAddress(), localPort() are called to find the address and
91 port that are currently bound to the socket. If the socket is
92 connected, peerAddress() and peerPort() determine the address and
93 port of the connected peer.
95 Finally, if any function should fail, error() and
96 errorString() can be called to determine the cause of the error.
99 #include <qabstracteventdispatcher.h>
100 #include <qsocketnotifier.h>
101 #include <qnetworkinterface.h>
103 #include "qnativesocketengine_p.h"
104 #include <private/qthread_p.h>
105 #include <private/qobject_p.h>
107 #if !defined(QT_NO_NETWORKPROXY)
108 # include "qnetworkproxy.h"
109 # include "qabstractsocket.h"
110 # include "qtcpserver.h"
115 //#define QNATIVESOCKETENGINE_DEBUG
120 #define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \
122 qWarning(""#function" was called on an uninitialized socket device"); \
123 return returnValue; \
125 #define Q_CHECK_INVALID_SOCKETLAYER(function, returnValue) do { \
127 qWarning(""#function" was called on an already initialized socket device"); \
128 return returnValue; \
130 #define Q_CHECK_STATE(function, checkState, returnValue) do { \
131 if (d->socketState != (checkState)) { \
132 qWarning(""#function" was not called in "#checkState); \
133 return (returnValue); \
135 #define Q_CHECK_NOT_STATE(function, checkState, returnValue) do { \
136 if (d->socketState == (checkState)) { \
137 qWarning(""#function" was called in "#checkState); \
138 return (returnValue); \
140 #define Q_CHECK_STATES(function, state1, state2, returnValue) do { \
141 if (d->socketState != (state1) && d->socketState != (state2)) { \
142 qWarning(""#function" was called" \
143 " not in "#state1" or "#state2); \
144 return (returnValue); \
146 #define Q_CHECK_TYPE(function, type, returnValue) do { \
147 if (d->socketType != (type)) { \
148 qWarning(#function" was called by a" \
149 " socket other than "#type""); \
150 return (returnValue); \
152 #define Q_TR(a) QT_TRANSLATE_NOOP(QNativeSocketEngine, a)
155 Constructs the private class and initializes all data members.
157 On Windows, WSAStartup is called "recursively" for every
158 concurrent QNativeSocketEngine. This is safe, because WSAStartup and
159 WSACleanup are reference counted.
161 QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() :
162 socketDescriptor(-1),
170 Destructs the private class.
172 QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate()
178 Sets the error and error string if not set already. The only
179 interesting error is the first one that occurred, and not the last
182 void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const
184 if (hasSetSocketError) {
185 // Only set socket errors once for one engine; expect the
186 // socket to recreate its engine after an error. Note: There's
187 // one exception: SocketError(11) bypasses this as it's purely
188 // a temporary internal error condition.
189 // Another exception is the way the waitFor*() functions set
190 // an error when a timeout occurs. After the call to setError()
191 // they reset the hasSetSocketError to false
194 if (error != QAbstractSocket::SocketError(11))
195 hasSetSocketError = true;
199 switch (errorString) {
200 case NonBlockingInitFailedErrorString:
201 socketErrorString = QNativeSocketEngine::tr("Unable to initialize non-blocking socket");
203 case BroadcastingInitFailedErrorString:
204 socketErrorString = QNativeSocketEngine::tr("Unable to initialize broadcast socket");
206 // should not happen anymore
207 case NoIpV6ErrorString:
208 socketErrorString = QNativeSocketEngine::tr("Attempt to use IPv6 socket on a platform with no IPv6 support");
210 case RemoteHostClosedErrorString:
211 socketErrorString = QNativeSocketEngine::tr("The remote host closed the connection");
213 case TimeOutErrorString:
214 socketErrorString = QNativeSocketEngine::tr("Network operation timed out");
216 case ResourceErrorString:
217 socketErrorString = QNativeSocketEngine::tr("Out of resources");
219 case OperationUnsupportedErrorString:
220 socketErrorString = QNativeSocketEngine::tr("Unsupported socket operation");
222 case ProtocolUnsupportedErrorString:
223 socketErrorString = QNativeSocketEngine::tr("Protocol type not supported");
225 case InvalidSocketErrorString:
226 socketErrorString = QNativeSocketEngine::tr("Invalid socket descriptor");
228 case HostUnreachableErrorString:
229 socketErrorString = QNativeSocketEngine::tr("Host unreachable");
231 case NetworkUnreachableErrorString:
232 socketErrorString = QNativeSocketEngine::tr("Network unreachable");
234 case AccessErrorString:
235 socketErrorString = QNativeSocketEngine::tr("Permission denied");
237 case ConnectionTimeOutErrorString:
238 socketErrorString = QNativeSocketEngine::tr("Connection timed out");
240 case ConnectionRefusedErrorString:
241 socketErrorString = QNativeSocketEngine::tr("Connection refused");
243 case AddressInuseErrorString:
244 socketErrorString = QNativeSocketEngine::tr("The bound address is already in use");
246 case AddressNotAvailableErrorString:
247 socketErrorString = QNativeSocketEngine::tr("The address is not available");
249 case AddressProtectedErrorString:
250 socketErrorString = QNativeSocketEngine::tr("The address is protected");
252 case DatagramTooLargeErrorString:
253 socketErrorString = QNativeSocketEngine::tr("Datagram was too large to send");
255 case SendDatagramErrorString:
256 socketErrorString = QNativeSocketEngine::tr("Unable to send a message");
258 case ReceiveDatagramErrorString:
259 socketErrorString = QNativeSocketEngine::tr("Unable to receive a message");
261 case WriteErrorString:
262 socketErrorString = QNativeSocketEngine::tr("Unable to write");
264 case ReadErrorString:
265 socketErrorString = QNativeSocketEngine::tr("Network error");
267 case PortInuseErrorString:
268 socketErrorString = QNativeSocketEngine::tr("Another socket is already listening on the same port");
270 case NotSocketErrorString:
271 socketErrorString = QNativeSocketEngine::tr("Operation on non-socket");
273 case InvalidProxyTypeString:
274 socketErrorString = QNativeSocketEngine::tr("The proxy type is invalid for this operation");
276 case UnknownSocketErrorString:
277 socketErrorString = QNativeSocketEngine::tr("Unknown error");
282 bool QNativeSocketEnginePrivate::checkProxy(const QHostAddress &address)
284 if (address.isLoopback())
287 #if !defined(QT_NO_NETWORKPROXY)
288 QObject *parent = q_func()->parent();
290 if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(parent)) {
291 proxy = socket->proxy();
292 } else if (QTcpServer *server = qobject_cast<QTcpServer *>(parent)) {
293 proxy = server->proxy();
295 // no parent -> no proxy
299 if (proxy.type() == QNetworkProxy::DefaultProxy)
300 proxy = QNetworkProxy::applicationProxy();
302 if (proxy.type() != QNetworkProxy::DefaultProxy &&
303 proxy.type() != QNetworkProxy::NoProxy) {
304 // QNativeSocketEngine doesn't do proxies
305 setError(QAbstractSocket::UnsupportedSocketOperationError,
306 QNativeSocketEnginePrivate::InvalidProxyTypeString);
315 Constructs a QNativeSocketEngine.
319 QNativeSocketEngine::QNativeSocketEngine(QObject *parent)
320 : QAbstractSocketEngine(*new QNativeSocketEnginePrivate(), parent)
325 Destructs a QNativeSocketEngine.
327 QNativeSocketEngine::~QNativeSocketEngine()
333 Initializes a QNativeSocketEngine by creating a new socket of type \a
334 socketType and network layer protocol \a protocol. Returns true on
335 success; otherwise returns false.
337 If the socket was already initialized, this function closes the
338 socket before reeinitializing it.
340 The new socket is non-blocking, and for UDP sockets it's also
343 bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol protocol)
345 Q_D(QNativeSocketEngine);
350 if (!d->createNewSocket(socketType, protocol)) {
351 #if defined (QNATIVESOCKETENGINE_DEBUG)
352 QString typeStr = QLatin1String("UnknownSocketType");
353 if (socketType == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
354 else if (socketType == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
355 QString protocolStr = QLatin1String("UnknownProtocol");
356 if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
357 else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
358 qDebug("QNativeSocketEngine::initialize(type == %s, protocol == %s) failed: %s",
359 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(), d->socketErrorString.toLatin1().constData());
364 // Make the socket nonblocking.
365 if (!setOption(NonBlockingSocketOption, 1)) {
366 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
367 QNativeSocketEnginePrivate::NonBlockingInitFailedErrorString);
372 // Set the broadcasting flag if it's a UDP socket.
373 if (socketType == QAbstractSocket::UdpSocket
374 && !setOption(BroadcastSocketOption, 1)) {
375 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
376 QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
382 // Make sure we receive out-of-band data
383 if (socketType == QAbstractSocket::TcpSocket
384 && !setOption(ReceiveOutOfBandData, 1)) {
385 qWarning("QNativeSocketEngine::initialize unable to inline out-of-band data");
388 // Before Qt 4.6, we always set the send and receive buffer size to 49152 as
389 // this was found to be an optimal value. However, modern OS
390 // all have some kind of auto tuning for this and we therefore don't set
391 // this explictly anymore.
392 // If it introduces any performance regressions for Qt 4.6.x (x > 0) then
393 // it will be put back in.
395 // You can use tests/manual/qhttpnetworkconnection to test HTTP download speed
399 // setReceiveBufferSize(49152);
400 // setSendBufferSize(49152);
402 d->socketType = socketType;
403 d->socketProtocol = protocol;
409 Initializes the socket using \a socketDescriptor instead of
410 creating a new one. The socket type and network layer protocol are
411 determined automatically. The socket's state is set to \a
414 If the socket type is either TCP or UDP, it is made non-blocking.
415 UDP sockets are also broadcast enabled.
417 bool QNativeSocketEngine::initialize(qintptr socketDescriptor, QAbstractSocket::SocketState socketState)
419 Q_D(QNativeSocketEngine);
424 d->socketDescriptor = socketDescriptor;
426 // determine socket type and protocol
427 if (!d->fetchConnectionParameters()) {
428 #if defined (QNATIVESOCKETENGINE_DEBUG)
429 qDebug("QNativeSocketEngine::initialize(socketDescriptor == %i) failed: %s",
430 socketDescriptor, d->socketErrorString.toLatin1().constData());
432 d->socketDescriptor = -1;
436 if (d->socketType != QAbstractSocket::UnknownSocketType) {
437 // Make the socket nonblocking.
438 if (!setOption(NonBlockingSocketOption, 1)) {
439 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
440 QNativeSocketEnginePrivate::NonBlockingInitFailedErrorString);
445 // Set the broadcasting flag if it's a UDP socket.
446 if (d->socketType == QAbstractSocket::UdpSocket
447 && !setOption(BroadcastSocketOption, 1)) {
448 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
449 QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);
455 d->socketState = socketState;
460 Returns true if the socket is valid; otherwise returns false. A
461 socket is valid if it has not been successfully initialized, or if
464 bool QNativeSocketEngine::isValid() const
466 Q_D(const QNativeSocketEngine);
467 return d->socketDescriptor != -1;
471 Returns the native socket descriptor. Any use of this descriptor
472 stands the risk of being non-portable.
474 qintptr QNativeSocketEngine::socketDescriptor() const
476 Q_D(const QNativeSocketEngine);
477 return d->socketDescriptor;
481 Connects to the IP address and port specified by \a address and \a
482 port. If the connection is established, this function returns true
483 and the socket enters ConnectedState. Otherwise, false is
486 If false is returned, state() should be called to see if the
487 socket is in ConnectingState. If so, a delayed TCP connection is
488 taking place, and connectToHost() must be called again later to
489 determine if the connection was established successfully or
490 not. The second connection attempt must be made when the socket is
491 ready for writing. This state can be determined either by
492 connecting a QSocketNotifier to the socket descriptor returned by
493 socketDescriptor(), or by calling the blocking function
497 \snippet code/src_network_socket_qnativesocketengine.cpp 0
499 Otherwise, error() should be called to determine the cause of the
502 bool QNativeSocketEngine::connectToHost(const QHostAddress &address, quint16 port)
504 Q_D(QNativeSocketEngine);
505 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::connectToHost(), false);
507 if (!d->checkProxy(address))
510 Q_CHECK_STATES(QNativeSocketEngine::connectToHost(),
511 QAbstractSocket::UnconnectedState, QAbstractSocket::ConnectingState, false);
513 d->peerAddress = address;
515 bool connected = d->nativeConnect(address, port);
517 d->fetchConnectionParameters();
523 If there's a connection activity on the socket, process it. Then
524 notify our parent if there really was activity.
526 void QNativeSocketEngine::connectionNotification()
528 Q_D(QNativeSocketEngine);
529 Q_ASSERT(state() == QAbstractSocket::ConnectingState);
531 connectToHost(d->peerAddress, d->peerPort);
532 if (state() != QAbstractSocket::ConnectingState) {
534 QAbstractSocketEngine::connectionNotification();
539 Connects to the remote host name given by \a name on port \a
540 port. When this function is called, the upper-level will not
541 perform a hostname lookup.
543 The native socket engine does not support this operation,
544 but some other socket engines (notably proxy-based ones) do.
546 bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port)
550 Q_D(QNativeSocketEngine);
551 d->setError(QAbstractSocket::UnsupportedSocketOperationError,
552 QNativeSocketEnginePrivate::OperationUnsupportedErrorString);
557 Binds the socket to the address \a address and port \a
558 port. Returns true on success; otherwise false is returned. The
559 port may be 0, in which case an arbitrary unused port is assigned
560 automatically by the operating system.
562 Servers call this function to set up the server's address and
563 port. TCP servers must in addition call listen() after bind().
565 bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
567 Q_D(QNativeSocketEngine);
568 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::bind(), false);
570 if (!d->checkProxy(address))
573 Q_CHECK_STATE(QNativeSocketEngine::bind(), QAbstractSocket::UnconnectedState, false);
575 if (!d->nativeBind(address, port))
578 d->fetchConnectionParameters();
583 Prepares a TCP server for accepting incoming connections. This
584 function must be called after bind(), and only by TCP sockets.
586 After this function has been called, pending client connections
587 are detected by checking if the socket is ready for reading. This
588 can be done by either creating a QSocketNotifier, passing the
589 socket descriptor returned by socketDescriptor(), or by calling
590 the blocking function waitForRead().
593 \snippet code/src_network_socket_qnativesocketengine.cpp 1
597 bool QNativeSocketEngine::listen()
599 Q_D(QNativeSocketEngine);
600 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::listen(), false);
601 Q_CHECK_STATE(QNativeSocketEngine::listen(), QAbstractSocket::BoundState, false);
602 Q_CHECK_TYPE(QNativeSocketEngine::listen(), QAbstractSocket::TcpSocket, false);
604 // We're using a backlog of 50. Most modern kernels support TCP
605 // syncookies by default, and if they do, the backlog is ignored.
606 // When there is no support for TCP syncookies, this value is
608 return d->nativeListen(50);
612 Accepts a pending connection from the socket, which must be in
613 ListeningState, and returns its socket descriptor. If no pending
614 connections are available, -1 is returned.
618 int QNativeSocketEngine::accept()
620 Q_D(QNativeSocketEngine);
621 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::accept(), -1);
622 Q_CHECK_STATE(QNativeSocketEngine::accept(), QAbstractSocket::ListeningState, false);
623 Q_CHECK_TYPE(QNativeSocketEngine::accept(), QAbstractSocket::TcpSocket, false);
625 return d->nativeAccept();
628 #ifndef QT_NO_NETWORKINTERFACE
633 bool QNativeSocketEngine::joinMulticastGroup(const QHostAddress &groupAddress,
634 const QNetworkInterface &iface)
636 Q_D(QNativeSocketEngine);
637 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::joinMulticastGroup(), false);
638 Q_CHECK_STATE(QNativeSocketEngine::joinMulticastGroup(), QAbstractSocket::BoundState, false);
639 Q_CHECK_TYPE(QNativeSocketEngine::joinMulticastGroup(), QAbstractSocket::UdpSocket, false);
641 // if the user binds a socket to an IPv6 address (or QHostAddress::Any) and
642 // then attempts to join an IPv4 multicast group, this won't work on
643 // Windows. In order to make this cross-platform, we warn & fail on all
645 if (groupAddress.protocol() == QAbstractSocket::IPv4Protocol &&
646 (d->socketProtocol == QAbstractSocket::IPv6Protocol ||
647 d->socketProtocol == QAbstractSocket::AnyIPProtocol)) {
648 qWarning("QAbstractSocket: cannot bind to QHostAddress::Any (or an IPv6 address) and join an IPv4 multicast group");
649 qWarning("QAbstractSocket: bind to QHostAddress::AnyIPv4 instead if you want to do this");
653 return d->nativeJoinMulticastGroup(groupAddress, iface);
659 bool QNativeSocketEngine::leaveMulticastGroup(const QHostAddress &groupAddress,
660 const QNetworkInterface &iface)
662 Q_D(QNativeSocketEngine);
663 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::leaveMulticastGroup(), false);
664 Q_CHECK_STATE(QNativeSocketEngine::leaveMulticastGroup(), QAbstractSocket::BoundState, false);
665 Q_CHECK_TYPE(QNativeSocketEngine::leaveMulticastGroup(), QAbstractSocket::UdpSocket, false);
666 return d->nativeLeaveMulticastGroup(groupAddress, iface);
670 QNetworkInterface QNativeSocketEngine::multicastInterface() const
672 Q_D(const QNativeSocketEngine);
673 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::multicastInterface(), QNetworkInterface());
674 Q_CHECK_TYPE(QNativeSocketEngine::multicastInterface(), QAbstractSocket::UdpSocket, QNetworkInterface());
675 return d->nativeMulticastInterface();
679 bool QNativeSocketEngine::setMulticastInterface(const QNetworkInterface &iface)
681 Q_D(QNativeSocketEngine);
682 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setMulticastInterface(), false);
683 Q_CHECK_TYPE(QNativeSocketEngine::setMulticastInterface(), QAbstractSocket::UdpSocket, false);
684 return d->nativeSetMulticastInterface(iface);
687 #endif // QT_NO_NETWORKINTERFACE
690 Returns the number of bytes that are currently available for
691 reading. On error, -1 is returned.
693 For UDP sockets, this function returns the accumulated size of all
694 pending datagrams, and it is therefore more useful for UDP sockets
695 to call hasPendingDatagrams() and pendingDatagramSize().
697 qint64 QNativeSocketEngine::bytesAvailable() const
699 Q_D(const QNativeSocketEngine);
700 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::bytesAvailable(), -1);
701 Q_CHECK_NOT_STATE(QNativeSocketEngine::bytesAvailable(), QAbstractSocket::UnconnectedState, false);
703 return d->nativeBytesAvailable();
707 Returns true if there is at least one datagram pending. This
708 function is only called by UDP sockets, where a datagram can have
709 a size of 0. TCP sockets call bytesAvailable().
711 bool QNativeSocketEngine::hasPendingDatagrams() const
713 Q_D(const QNativeSocketEngine);
714 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::hasPendingDatagrams(), false);
715 Q_CHECK_NOT_STATE(QNativeSocketEngine::hasPendingDatagrams(), QAbstractSocket::UnconnectedState, false);
716 Q_CHECK_TYPE(QNativeSocketEngine::hasPendingDatagrams(), QAbstractSocket::UdpSocket, false);
718 return d->nativeHasPendingDatagrams();
722 Returns the size of the pending datagram, or -1 if no datagram is
723 pending. A datagram size of 0 is perfectly valid. This function is
724 called by UDP sockets before receiveMessage(). For TCP sockets,
725 call bytesAvailable().
727 qint64 QNativeSocketEngine::pendingDatagramSize() const
729 Q_D(const QNativeSocketEngine);
730 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::pendingDatagramSize(), -1);
731 Q_CHECK_TYPE(QNativeSocketEngine::pendingDatagramSize(), QAbstractSocket::UdpSocket, false);
733 return d->nativePendingDatagramSize();
737 Reads up to \a maxSize bytes of a datagram from the socket,
738 stores it in \a data and returns the number of bytes read. The
739 address and port of the sender are stored in \a address and \a
740 port. If either of these pointers is 0, the corresponding value is
743 To avoid unnecessarily loss of data, call pendingDatagramSize() to
744 determine the size of the pending message before reading it. If \a
745 maxSize is too small, the rest of the datagram will be lost.
747 Returns -1 if an error occurred.
749 \sa hasPendingDatagrams()
751 qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
754 Q_D(QNativeSocketEngine);
755 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::readDatagram(), -1);
756 Q_CHECK_TYPE(QNativeSocketEngine::readDatagram(), QAbstractSocket::UdpSocket, false);
758 return d->nativeReceiveDatagram(data, maxSize, address, port);
762 Writes a UDP datagram of size \a size bytes to the socket from
763 \a data to the address \a host on port \a port, and returns the
764 number of bytes written, or -1 if an error occurred.
766 Only one datagram is sent, and if there is too much data to fit
767 into a single datagram, the operation will fail and error()
768 will return QAbstractSocket::DatagramTooLargeError. Operating systems impose an
769 upper limit to the size of a datagram, but this size is different
770 on almost all platforms. Sending large datagrams is in general
771 disadvised, as even if they are sent successfully, they are likely
772 to be fragmented before arriving at their destination.
774 Experience has shown that it is in general safe to send datagrams
775 no larger than 512 bytes.
779 qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 size,
780 const QHostAddress &host, quint16 port)
782 Q_D(QNativeSocketEngine);
783 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::writeDatagram(), -1);
784 Q_CHECK_TYPE(QNativeSocketEngine::writeDatagram(), QAbstractSocket::UdpSocket, -1);
785 return d->nativeSendDatagram(data, size, host, port);
789 Writes a block of \a size bytes from \a data to the socket.
790 Returns the number of bytes written, or -1 if an error occurred.
792 qint64 QNativeSocketEngine::write(const char *data, qint64 size)
794 Q_D(QNativeSocketEngine);
795 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::write(), -1);
796 Q_CHECK_STATE(QNativeSocketEngine::write(), QAbstractSocket::ConnectedState, -1);
797 return d->nativeWrite(data, size);
801 qint64 QNativeSocketEngine::bytesToWrite() const
807 Reads up to \a maxSize bytes into \a data from the socket.
808 Returns the number of bytes read, or -1 if an error occurred.
810 qint64 QNativeSocketEngine::read(char *data, qint64 maxSize)
812 Q_D(QNativeSocketEngine);
813 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::read(), -1);
814 Q_CHECK_STATES(QNativeSocketEngine::read(), QAbstractSocket::ConnectedState, QAbstractSocket::BoundState, -1);
816 qint64 readBytes = d->nativeRead(data, maxSize);
818 // Handle remote close
819 if (readBytes == 0 && d->socketType == QAbstractSocket::TcpSocket) {
820 d->setError(QAbstractSocket::RemoteHostClosedError,
821 QNativeSocketEnginePrivate::RemoteHostClosedErrorString);
824 } else if (readBytes == -1) {
825 if (!d->hasSetSocketError) {
826 d->hasSetSocketError = true;
827 d->socketError = QAbstractSocket::NetworkError;
828 d->socketErrorString = qt_error_string();
837 Closes the socket. In order to use the socket again, initialize()
840 void QNativeSocketEngine::close()
842 Q_D(QNativeSocketEngine);
844 d->readNotifier->setEnabled(false);
845 if (d->writeNotifier)
846 d->writeNotifier->setEnabled(false);
847 if (d->exceptNotifier)
848 d->exceptNotifier->setEnabled(false);
850 if(d->socketDescriptor != -1) {
852 d->socketDescriptor = -1;
854 d->socketState = QAbstractSocket::UnconnectedState;
855 d->hasSetSocketError = false;
857 d->localAddress.clear();
859 d->peerAddress.clear();
860 if (d->readNotifier) {
861 qDeleteInEventHandler(d->readNotifier);
864 if (d->writeNotifier) {
865 qDeleteInEventHandler(d->writeNotifier);
866 d->writeNotifier = 0;
868 if (d->exceptNotifier) {
869 qDeleteInEventHandler(d->exceptNotifier);
870 d->exceptNotifier = 0;
875 Waits for \a msecs milliseconds or until the socket is ready for
876 reading. If \a timedOut is not 0 and \a msecs milliseconds have
877 passed, the value of \a timedOut is set to true.
879 Returns true if data is available for reading; otherwise returns
882 This is a blocking function call; its use is disadvised in a
883 single threaded application, as the whole thread will stop
884 responding until the function returns. waitForRead() is most
885 useful when there is no event loop available. The general approach
886 is to create a QSocketNotifier, passing the socket descriptor
887 returned by socketDescriptor() to its constructor.
889 bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
891 Q_D(const QNativeSocketEngine);
892 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForRead(), false);
893 Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForRead(),
894 QAbstractSocket::UnconnectedState, false);
899 int ret = d->nativeSelect(msecs, true);
903 d->setError(QAbstractSocket::SocketTimeoutError,
904 QNativeSocketEnginePrivate::TimeOutErrorString);
905 d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
907 } else if (state() == QAbstractSocket::ConnectingState) {
908 connectToHost(d->peerAddress, d->peerPort);
915 Waits for \a msecs milliseconds or until the socket is ready for
916 writing. If \a timedOut is not 0 and \a msecs milliseconds have
917 passed, the value of \a timedOut is set to true.
919 Returns true if data is available for writing; otherwise returns
922 This is a blocking function call; its use is disadvised in a
923 single threaded application, as the whole thread will stop
924 responding until the function returns. waitForWrite() is most
925 useful when there is no event loop available. The general approach
926 is to create a QSocketNotifier, passing the socket descriptor
927 returned by socketDescriptor() to its constructor.
929 bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut)
931 Q_D(QNativeSocketEngine);
932 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForWrite(), false);
933 Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForWrite(),
934 QAbstractSocket::UnconnectedState, false);
939 int ret = d->nativeSelect(msecs, false);
940 // On Windows, the socket is in connected state if a call to
941 // select(writable) is successful. In this case we should not
942 // issue a second call to WSAConnect()
943 #if defined (Q_OS_WIN)
945 setState(QAbstractSocket::ConnectedState);
946 d_func()->fetchConnectionParameters();
950 int valueSize = sizeof(value);
951 if (::getsockopt(d->socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
952 if (value == WSAECONNREFUSED) {
953 d->setError(QAbstractSocket::ConnectionRefusedError, QNativeSocketEnginePrivate::ConnectionRefusedErrorString);
954 d->socketState = QAbstractSocket::UnconnectedState;
956 } else if (value == WSAETIMEDOUT) {
957 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::ConnectionTimeOutErrorString);
958 d->socketState = QAbstractSocket::UnconnectedState;
960 } else if (value == WSAEHOSTUNREACH) {
961 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::HostUnreachableErrorString);
962 d->socketState = QAbstractSocket::UnconnectedState;
972 d->setError(QAbstractSocket::SocketTimeoutError,
973 QNativeSocketEnginePrivate::TimeOutErrorString);
974 d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
976 } else if (state() == QAbstractSocket::ConnectingState) {
977 connectToHost(d->peerAddress, d->peerPort);
983 bool QNativeSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
984 bool checkRead, bool checkWrite,
985 int msecs, bool *timedOut)
987 Q_D(QNativeSocketEngine);
988 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForWrite(), false);
989 Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForReadOrWrite(),
990 QAbstractSocket::UnconnectedState, false);
992 int ret = d->nativeSelect(msecs, checkRead, checkWrite, readyToRead, readyToWrite);
993 // On Windows, the socket is in connected state if a call to
994 // select(writable) is successful. In this case we should not
995 // issue a second call to WSAConnect()
996 #if defined (Q_OS_WIN)
997 if (checkWrite && ((readyToWrite && *readyToWrite) || !readyToWrite) && ret > 0) {
998 setState(QAbstractSocket::ConnectedState);
999 d_func()->fetchConnectionParameters();
1003 int valueSize = sizeof(value);
1004 if (::getsockopt(d->socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
1005 if (value == WSAECONNREFUSED) {
1006 d->setError(QAbstractSocket::ConnectionRefusedError, QNativeSocketEnginePrivate::ConnectionRefusedErrorString);
1007 d->socketState = QAbstractSocket::UnconnectedState;
1009 } else if (value == WSAETIMEDOUT) {
1010 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::ConnectionTimeOutErrorString);
1011 d->socketState = QAbstractSocket::UnconnectedState;
1013 } else if (value == WSAEHOSTUNREACH) {
1014 d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::HostUnreachableErrorString);
1015 d->socketState = QAbstractSocket::UnconnectedState;
1024 d->setError(QAbstractSocket::SocketTimeoutError,
1025 QNativeSocketEnginePrivate::TimeOutErrorString);
1026 d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
1028 } else if (state() == QAbstractSocket::ConnectingState) {
1029 connectToHost(d->peerAddress, d->peerPort);
1036 Returns the size of the operating system's socket receive
1037 buffer. Depending on the operating system, this size may be
1038 different from what has been set earlier with
1039 setReceiveBufferSize().
1041 qint64 QNativeSocketEngine::receiveBufferSize() const
1043 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::receiveBufferSize(), -1);
1044 return option(ReceiveBufferSocketOption);
1048 Sets the size of the operating system receive buffer to \a size.
1050 For clients, this should be set before connectToHost() is called;
1051 otherwise it will have no effect. For servers, it should be called
1054 The operating system receive buffer size effectively limits two
1055 things: how much data can be in transit at any one moment, and how
1056 much data can be received in one iteration of the main event loop.
1057 Setting the size of the receive buffer may have an impact on the
1058 socket's performance.
1060 The default value is operating system-dependent.
1062 void QNativeSocketEngine::setReceiveBufferSize(qint64 size)
1064 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setReceiveBufferSize(), Q_VOID);
1065 setOption(ReceiveBufferSocketOption, size);
1069 Returns the size of the operating system send buffer. Depending on
1070 the operating system, this size may be different from what has
1071 been set earlier with setSendBufferSize().
1073 qint64 QNativeSocketEngine::sendBufferSize() const
1075 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setSendBufferSize(), -1);
1076 return option(SendBufferSocketOption);
1080 Sets the size of the operating system send buffer to \a size.
1082 The operating system send buffer size effectively limits how much
1083 data can be in transit at any one moment. Setting the size of the
1084 send buffer may have an impact on the socket's performance.
1086 The default value is operating system-dependent.
1088 void QNativeSocketEngine::setSendBufferSize(qint64 size)
1090 Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::setSendBufferSize(), Q_VOID);
1091 setOption(SendBufferSocketOption, size);
1096 Sets the option \a option to the value \a value.
1098 bool QNativeSocketEngine::setOption(SocketOption option, int value)
1100 Q_D(QNativeSocketEngine);
1101 return d->setOption(option, value);
1105 Returns the value of the option \a socketOption.
1107 int QNativeSocketEngine::option(SocketOption socketOption) const
1109 Q_D(const QNativeSocketEngine);
1110 return d->option(socketOption);
1113 bool QNativeSocketEngine::isReadNotificationEnabled() const
1115 Q_D(const QNativeSocketEngine);
1116 return d->readNotifier && d->readNotifier->isEnabled();
1121 \class QReadNotifier
1122 \brief The QReadNotifer class is used to improve performance.
1124 QReadNotifier is a private class used for performance reasons vs
1125 connecting to the QSocketNotifier activated() signal.
1127 class QReadNotifier : public QSocketNotifier
1130 QReadNotifier(qintptr fd, QNativeSocketEngine *parent)
1131 : QSocketNotifier(fd, QSocketNotifier::Read, parent)
1132 { engine = parent; }
1135 bool event(QEvent *);
1137 QNativeSocketEngine *engine;
1140 bool QReadNotifier::event(QEvent *e)
1142 if (e->type() == QEvent::SockAct) {
1143 engine->readNotification();
1146 return QSocketNotifier::event(e);
1151 \class QWriteNotifier
1152 \brief The QWriteNotifer class is used to improve performance.
1154 QWriteNotifier is a private class used for performance reasons vs
1155 connecting to the QSocketNotifier activated() signal.
1157 class QWriteNotifier : public QSocketNotifier
1160 QWriteNotifier(int fd, QNativeSocketEngine *parent)
1161 : QSocketNotifier(fd, QSocketNotifier::Write, parent) { engine = parent; }
1164 bool event(QEvent *);
1166 QNativeSocketEngine *engine;
1169 bool QWriteNotifier::event(QEvent *e)
1171 if (e->type() == QEvent::SockAct) {
1172 if (engine->state() == QAbstractSocket::ConnectingState)
1173 engine->connectionNotification();
1175 engine->writeNotification();
1178 return QSocketNotifier::event(e);
1181 class QExceptionNotifier : public QSocketNotifier
1184 QExceptionNotifier(int fd, QNativeSocketEngine *parent)
1185 : QSocketNotifier(fd, QSocketNotifier::Exception, parent) { engine = parent; }
1188 bool event(QEvent *);
1190 QNativeSocketEngine *engine;
1193 bool QExceptionNotifier::event(QEvent *e)
1195 if (e->type() == QEvent::SockAct) {
1196 if (engine->state() == QAbstractSocket::ConnectingState)
1197 engine->connectionNotification();
1199 engine->exceptionNotification();
1202 return QSocketNotifier::event(e);
1205 void QNativeSocketEngine::setReadNotificationEnabled(bool enable)
1207 Q_D(QNativeSocketEngine);
1208 if (d->readNotifier) {
1209 d->readNotifier->setEnabled(enable);
1210 } else if (enable && d->threadData->eventDispatcher) {
1211 d->readNotifier = new QReadNotifier(d->socketDescriptor, this);
1212 d->readNotifier->setEnabled(true);
1216 bool QNativeSocketEngine::isWriteNotificationEnabled() const
1218 Q_D(const QNativeSocketEngine);
1219 return d->writeNotifier && d->writeNotifier->isEnabled();
1222 void QNativeSocketEngine::setWriteNotificationEnabled(bool enable)
1224 Q_D(QNativeSocketEngine);
1225 if (d->writeNotifier) {
1226 d->writeNotifier->setEnabled(enable);
1227 } else if (enable && d->threadData->eventDispatcher) {
1228 d->writeNotifier = new QWriteNotifier(d->socketDescriptor, this);
1229 d->writeNotifier->setEnabled(true);
1233 bool QNativeSocketEngine::isExceptionNotificationEnabled() const
1235 Q_D(const QNativeSocketEngine);
1236 return d->exceptNotifier && d->exceptNotifier->isEnabled();
1239 void QNativeSocketEngine::setExceptionNotificationEnabled(bool enable)
1241 Q_D(QNativeSocketEngine);
1242 if (d->exceptNotifier) {
1243 d->exceptNotifier->setEnabled(enable);
1244 } else if (enable && d->threadData->eventDispatcher) {
1245 d->exceptNotifier = new QExceptionNotifier(d->socketDescriptor, this);
1246 d->exceptNotifier->setEnabled(true);