Doc: Modularize QtNetwork documentation.
[profile/ivi/qtbase.git] / src / network / socket / qudpsocket.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 //#define QUDPSOCKET_DEBUG
43
44 /*! \class QUdpSocket
45
46     \reentrant
47     \brief The QUdpSocket class provides a UDP socket.
48
49     \ingroup network
50     \inmodule QtNetwork
51
52     UDP (User Datagram Protocol) is a lightweight, unreliable,
53     datagram-oriented, connectionless protocol. It can be used when
54     reliability isn't important. QUdpSocket is a subclass of
55     QAbstractSocket that allows you to send and receive UDP
56     datagrams.
57
58     The most common way to use this class is to bind to an address and port
59     using bind(), then call writeDatagram() and readDatagram() to transfer
60     data. If you want to use the standard QIODevice functions read(),
61     readLine(), write(), etc., you must first connect the socket directly to a
62     peer by calling connectToHost().
63
64     The socket emits the bytesWritten() signal every time a datagram
65     is written to the network. If you just want to send datagrams,
66     you don't need to call bind().
67
68     The readyRead() signal is emitted whenever datagrams arrive. In
69     that case, hasPendingDatagrams() returns true. Call
70     pendingDatagramSize() to obtain the size of the first pending
71     datagram, and readDatagram() to read it.
72
73     \note An incoming datagram should be read when you receive the readyRead()
74     signal, otherwise this signal will not be emitted for the next datagram.
75
76     Example:
77
78     \snippet code/src_network_socket_qudpsocket.cpp 0
79
80     QUdpSocket also supports UDP multicast. Use joinMulticastGroup() and
81     leaveMulticastGroup() to control group membership, and
82     QAbstractSocket::MulticastTtlOption and
83     QAbstractSocket::MulticastLoopbackOption to set the TTL and loopback socket
84     options. Use setMulticastInterface() to control the outgoing interface for
85     multicast datagrams, and multicastInterface() to query it.
86
87     With QUdpSocket, you can also establish a virtual connection to a
88     UDP server using connectToHost() and then use read() and write()
89     to exchange datagrams without specifying the receiver for each
90     datagram.
91
92     The \l{network/broadcastsender}{Broadcast Sender},
93     \l{network/broadcastreceiver}{Broadcast Receiver},
94     \l{network/multicastsender}{Multicast Sender}, and
95     \l{network/multicastreceiver}{Multicast Receiver} examples illustrate how
96     to use QUdpSocket in applications.
97
98     \sa QTcpSocket
99 */
100
101 #include "qhostaddress.h"
102 #include "qnetworkinterface.h"
103 #include "qabstractsocket_p.h"
104 #include "qudpsocket.h"
105
106 QT_BEGIN_NAMESPACE
107
108 #ifndef QT_NO_UDPSOCKET
109
110 #define QT_CHECK_BOUND(function, a) do { \
111     if (!isValid()) { \
112         qWarning(function" called on a QUdpSocket when not in QUdpSocket::BoundState"); \
113         return (a); \
114     } } while (0)
115
116 class QUdpSocketPrivate : public QAbstractSocketPrivate
117 {
118     Q_DECLARE_PUBLIC(QUdpSocket)
119
120     bool doEnsureInitialized(const QHostAddress &bindAddress, quint16 bindPort,
121                              const QHostAddress &remoteAddress);
122 public:
123     inline bool ensureInitialized(const QHostAddress &bindAddress, quint16 bindPort)
124     { return doEnsureInitialized(bindAddress, bindPort, QHostAddress()); }
125
126     inline bool ensureInitialized(const QHostAddress &remoteAddress)
127     { return doEnsureInitialized(QHostAddress(), 0, remoteAddress); }
128 };
129
130 bool QUdpSocketPrivate::doEnsureInitialized(const QHostAddress &bindAddress, quint16 bindPort,
131                                             const QHostAddress &remoteAddress)
132 {
133     const QHostAddress *address = &bindAddress;
134     QAbstractSocket::NetworkLayerProtocol proto = address->protocol();
135     if (proto == QUdpSocket::UnknownNetworkLayerProtocol) {
136         address = &remoteAddress;
137         proto = address->protocol();
138     }
139
140     // now check if the socket engine is initialized and to the right type
141     if (!socketEngine || !socketEngine->isValid()) {
142         resolveProxy(remoteAddress.toString(), bindPort);
143         if (!initSocketLayer(address->protocol()))
144             return false;
145     }
146
147     return true;
148 }
149
150 /*!
151     Creates a QUdpSocket object.
152
153     \a parent is passed to the QObject constructor.
154
155     \sa socketType()
156 */
157 QUdpSocket::QUdpSocket(QObject *parent)
158     : QAbstractSocket(UdpSocket, *new QUdpSocketPrivate, parent)
159 {
160     d_func()->isBuffered = false;
161 }
162
163 /*!
164     Destroys the socket, closing the connection if necessary.
165
166     \sa close()
167 */
168 QUdpSocket::~QUdpSocket()
169 {
170 }
171
172 #ifndef QT_NO_NETWORKINTERFACE
173
174 /*!
175     \since 4.8
176
177     Joins the the multicast group specified by \a groupAddress on the default
178     interface chosen by the operating system. The socket must be in BoundState,
179     otherwise an error occurs.
180
181     Note that if you are attempting to join an IPv4 group, your socket must not
182     be bound using IPv6 (or in dual mode, using QHostAddress::Any). You must use
183     QHostAddress::AnyIPv4 instead.
184
185     This function returns true if successful; otherwise it returns false
186     and sets the socket error accordingly.
187
188     \sa leaveMulticastGroup()
189 */
190 bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress)
191 {
192     return joinMulticastGroup(groupAddress, QNetworkInterface());
193 }
194
195 /*!
196     \since 4.8
197     \overload
198
199     Joins the multicast group address \a groupAddress on the interface \a
200     iface.
201
202     \sa leaveMulticastGroup()
203 */
204 bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress,
205                                     const QNetworkInterface &iface)
206 {
207     Q_D(QUdpSocket);
208     QT_CHECK_BOUND("QUdpSocket::joinMulticastGroup()", false);
209     return d->socketEngine->joinMulticastGroup(groupAddress, iface);
210 }
211
212 /*!
213     \since 4.8
214
215     Leaves the multicast group specified by \a groupAddress on the default
216     interface chosen by the operating system. The socket must be in BoundState,
217     otherwise an error occurs.
218
219    This function returns true if successful; otherwise it returns false and
220    sets the socket error accordingly.
221
222    \sa joinMulticastGroup()
223 */
224 bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress)
225 {
226     return leaveMulticastGroup(groupAddress, QNetworkInterface());
227 }
228
229 /*!
230     \since 4.8
231     \overload
232
233     Leaves the multicast group specified by \a groupAddress on the interface \a
234     iface.
235
236     \sa joinMulticastGroup()
237 */
238 bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress,
239                                      const QNetworkInterface &iface)
240 {
241     QT_CHECK_BOUND("QUdpSocket::leaveMulticastGroup()", false);
242     return d_func()->socketEngine->leaveMulticastGroup(groupAddress, iface);
243 }
244
245 /*!
246     \since 4.8
247
248     Returns the interface for the outgoing interface for multicast datagrams.
249     This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and
250     the IPV6_MULTICAST_IF socket option for IPv6 sockets. If no interface has
251     been previously set, this function returns an invalid QNetworkInterface.
252     The socket must be in BoundState, otherwise an invalid QNetworkInterface is
253     returned.
254
255     \sa setMulticastInterface()
256 */
257 QNetworkInterface QUdpSocket::multicastInterface() const
258 {
259     Q_D(const QUdpSocket);
260     QT_CHECK_BOUND("QUdpSocket::multicastInterface()", QNetworkInterface());
261     return d->socketEngine->multicastInterface();
262 }
263
264 /*!
265     \since 4.8
266
267     Sets the outgoing interface for multicast datagrams to the interface \a
268     iface. This corresponds to the IP_MULTICAST_IF socket option for IPv4
269     sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. The
270     socket must be in BoundState, otherwise this function does nothing.
271
272     \sa multicastInterface(), joinMulticastGroup(), leaveMulticastGroup()
273 */
274 void QUdpSocket::setMulticastInterface(const QNetworkInterface &iface)
275 {
276     Q_D(QUdpSocket);
277     if (!isValid()) {
278         qWarning("QUdpSocket::setMulticastInterface() called on a QUdpSocket when not in QUdpSocket::BoundState");
279         return;
280     }
281     d->socketEngine->setMulticastInterface(iface);
282 }
283
284 #endif // QT_NO_NETWORKINTERFACE
285
286 /*!
287     Returns true if at least one datagram is waiting to be read;
288     otherwise returns false.
289
290     \sa pendingDatagramSize(), readDatagram()
291 */
292 bool QUdpSocket::hasPendingDatagrams() const
293 {
294     QT_CHECK_BOUND("QUdpSocket::hasPendingDatagrams()", false);
295     return d_func()->socketEngine->hasPendingDatagrams();
296 }
297
298 /*!
299     Returns the size of the first pending UDP datagram. If there is
300     no datagram available, this function returns -1.
301
302     \sa hasPendingDatagrams(), readDatagram()
303 */
304 qint64 QUdpSocket::pendingDatagramSize() const
305 {
306     QT_CHECK_BOUND("QUdpSocket::pendingDatagramSize()", -1);
307     return d_func()->socketEngine->pendingDatagramSize();
308 }
309
310 /*!
311     Sends the datagram at \a data of size \a size to the host
312     address \a address at port \a port. Returns the number of
313     bytes sent on success; otherwise returns -1.
314
315     Datagrams are always written as one block. The maximum size of a
316     datagram is highly platform-dependent, but can be as low as 8192
317     bytes. If the datagram is too large, this function will return -1
318     and error() will return DatagramTooLargeError.
319
320     Sending datagrams larger than 512 bytes is in general disadvised,
321     as even if they are sent successfully, they are likely to be
322     fragmented by the IP layer before arriving at their final
323     destination.
324
325     \warning Calling this function on a connected UDP socket may
326     result in an error and no packet being sent. If you are using a
327     connected socket, use write() to send datagrams.
328
329     \sa readDatagram(), write()
330 */
331 qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address,
332                                   quint16 port)
333 {
334     Q_D(QUdpSocket);
335 #if defined QUDPSOCKET_DEBUG
336     qDebug("QUdpSocket::writeDatagram(%p, %llu, \"%s\", %i)", data, size,
337            address.toString().toLatin1().constData(), port);
338 #endif
339     if (!d->doEnsureInitialized(QHostAddress::Any, 0, address))
340         return -1;
341     if (state() == UnconnectedState)
342         bind();
343
344     qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
345     d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
346
347     if (sent >= 0) {
348         emit bytesWritten(sent);
349     } else {
350         d->socketError = d->socketEngine->error();
351         setErrorString(d->socketEngine->errorString());
352         emit error(d->socketError);
353     }
354     return sent;
355 }
356
357 /*!
358     \fn qint64 QUdpSocket::writeDatagram(const QByteArray &datagram,
359                                              const QHostAddress &host, quint16 port)
360     \overload
361
362     Sends the datagram \a datagram to the host address \a host and at
363     port \a port.
364 */
365
366 /*!
367     Receives a datagram no larger than \a maxSize bytes and stores
368     it in \a data. The sender's host address and port is stored in
369     *\a address and *\a port (unless the pointers are 0).
370
371     Returns the size of the datagram on success; otherwise returns
372     -1.
373
374     If \a maxSize is too small, the rest of the datagram will be
375     lost. To avoid loss of data, call pendingDatagramSize() to
376     determine the size of the pending datagram before attempting to
377     read it. If \a maxSize is 0, the datagram will be discarded.
378
379     \sa writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()
380 */
381 qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
382                                     quint16 *port)
383 {
384     Q_D(QUdpSocket);
385
386 #if defined QUDPSOCKET_DEBUG
387     qDebug("QUdpSocket::readDatagram(%p, %llu, %p, %p)", data, maxSize, address, port);
388 #endif
389     QT_CHECK_BOUND("QUdpSocket::readDatagram()", -1);
390     qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
391     d_func()->socketEngine->setReadNotificationEnabled(true);
392     if (readBytes < 0) {
393         d->socketError = d->socketEngine->error();
394         setErrorString(d->socketEngine->errorString());
395         emit error(d->socketError);
396     }
397     return readBytes;
398 }
399 #endif // QT_NO_UDPSOCKET
400
401 QT_END_NAMESPACE