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 QUDPSOCKET_DEBUG
47 \brief The QUdpSocket class provides a UDP socket.
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
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().
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().
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.
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.
78 \snippet code/src_network_socket_qudpsocket.cpp 0
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.
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
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.
101 #include "qhostaddress.h"
102 #include "qnetworkinterface.h"
103 #include "qabstractsocket_p.h"
104 #include "qudpsocket.h"
108 #ifndef QT_NO_UDPSOCKET
110 #define QT_CHECK_BOUND(function, a) do { \
112 qWarning(function" called on a QUdpSocket when not in QUdpSocket::BoundState"); \
116 class QUdpSocketPrivate : public QAbstractSocketPrivate
118 Q_DECLARE_PUBLIC(QUdpSocket)
120 bool doEnsureInitialized(const QHostAddress &bindAddress, quint16 bindPort,
121 const QHostAddress &remoteAddress);
123 inline bool ensureInitialized(const QHostAddress &bindAddress, quint16 bindPort)
124 { return doEnsureInitialized(bindAddress, bindPort, QHostAddress()); }
126 inline bool ensureInitialized(const QHostAddress &remoteAddress)
127 { return doEnsureInitialized(QHostAddress(), 0, remoteAddress); }
130 bool QUdpSocketPrivate::doEnsureInitialized(const QHostAddress &bindAddress, quint16 bindPort,
131 const QHostAddress &remoteAddress)
133 const QHostAddress *address = &bindAddress;
134 QAbstractSocket::NetworkLayerProtocol proto = address->protocol();
135 if (proto == QUdpSocket::UnknownNetworkLayerProtocol) {
136 address = &remoteAddress;
137 proto = address->protocol();
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()))
151 Creates a QUdpSocket object.
153 \a parent is passed to the QObject constructor.
157 QUdpSocket::QUdpSocket(QObject *parent)
158 : QAbstractSocket(UdpSocket, *new QUdpSocketPrivate, parent)
160 d_func()->isBuffered = false;
164 Destroys the socket, closing the connection if necessary.
168 QUdpSocket::~QUdpSocket()
172 #ifndef QT_NO_NETWORKINTERFACE
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.
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.
185 This function returns true if successful; otherwise it returns false
186 and sets the socket error accordingly.
188 \sa leaveMulticastGroup()
190 bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress)
192 return joinMulticastGroup(groupAddress, QNetworkInterface());
199 Joins the multicast group address \a groupAddress on the interface \a
202 \sa leaveMulticastGroup()
204 bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress,
205 const QNetworkInterface &iface)
208 QT_CHECK_BOUND("QUdpSocket::joinMulticastGroup()", false);
209 return d->socketEngine->joinMulticastGroup(groupAddress, iface);
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.
219 This function returns true if successful; otherwise it returns false and
220 sets the socket error accordingly.
222 \sa joinMulticastGroup()
224 bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress)
226 return leaveMulticastGroup(groupAddress, QNetworkInterface());
233 Leaves the multicast group specified by \a groupAddress on the interface \a
236 \sa joinMulticastGroup()
238 bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress,
239 const QNetworkInterface &iface)
241 QT_CHECK_BOUND("QUdpSocket::leaveMulticastGroup()", false);
242 return d_func()->socketEngine->leaveMulticastGroup(groupAddress, iface);
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
255 \sa setMulticastInterface()
257 QNetworkInterface QUdpSocket::multicastInterface() const
259 Q_D(const QUdpSocket);
260 QT_CHECK_BOUND("QUdpSocket::multicastInterface()", QNetworkInterface());
261 return d->socketEngine->multicastInterface();
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.
272 \sa multicastInterface(), joinMulticastGroup(), leaveMulticastGroup()
274 void QUdpSocket::setMulticastInterface(const QNetworkInterface &iface)
278 qWarning("QUdpSocket::setMulticastInterface() called on a QUdpSocket when not in QUdpSocket::BoundState");
281 d->socketEngine->setMulticastInterface(iface);
284 #endif // QT_NO_NETWORKINTERFACE
287 Returns true if at least one datagram is waiting to be read;
288 otherwise returns false.
290 \sa pendingDatagramSize(), readDatagram()
292 bool QUdpSocket::hasPendingDatagrams() const
294 QT_CHECK_BOUND("QUdpSocket::hasPendingDatagrams()", false);
295 return d_func()->socketEngine->hasPendingDatagrams();
299 Returns the size of the first pending UDP datagram. If there is
300 no datagram available, this function returns -1.
302 \sa hasPendingDatagrams(), readDatagram()
304 qint64 QUdpSocket::pendingDatagramSize() const
306 QT_CHECK_BOUND("QUdpSocket::pendingDatagramSize()", -1);
307 return d_func()->socketEngine->pendingDatagramSize();
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.
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.
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
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.
329 \sa readDatagram(), write()
331 qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address,
335 #if defined QUDPSOCKET_DEBUG
336 qDebug("QUdpSocket::writeDatagram(%p, %llu, \"%s\", %i)", data, size,
337 address.toString().toLatin1().constData(), port);
339 if (!d->doEnsureInitialized(QHostAddress::Any, 0, address))
341 if (state() == UnconnectedState)
344 qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
345 d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
348 emit bytesWritten(sent);
350 d->socketError = d->socketEngine->error();
351 setErrorString(d->socketEngine->errorString());
352 emit error(d->socketError);
358 \fn qint64 QUdpSocket::writeDatagram(const QByteArray &datagram,
359 const QHostAddress &host, quint16 port)
362 Sends the datagram \a datagram to the host address \a host and at
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).
371 Returns the size of the datagram on success; otherwise returns
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.
379 \sa writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()
381 qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
386 #if defined QUDPSOCKET_DEBUG
387 qDebug("QUdpSocket::readDatagram(%p, %llu, %p, %p)", data, maxSize, address, port);
389 QT_CHECK_BOUND("QUdpSocket::readDatagram()", -1);
390 qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
391 d_func()->socketEngine->setReadNotificationEnabled(true);
393 d->socketError = d->socketEngine->error();
394 setErrorString(d->socketEngine->errorString());
395 emit error(d->socketError);
399 #endif // QT_NO_UDPSOCKET