socket/qudpsocket.cpp

Source codeSwitch to Preprocessed file
LineSource CodeCoverage
1/**************************************************************************** -
2** -
3** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -
4** Contact: http://www.qt-project.org/legal -
5** -
6** This file is part of the QtNetwork module of the Qt Toolkit. -
7** -
8** $QT_BEGIN_LICENSE:LGPL$ -
9** Commercial License Usage -
10** Licensees holding valid commercial Qt licenses may use this file in -
11** accordance with the commercial license agreement provided with the -
12** Software or, alternatively, in accordance with the terms contained in -
13** a written agreement between you and Digia. For licensing terms and -
14** conditions see http://qt.digia.com/licensing. For further information -
15** use the contact form at http://qt.digia.com/contact-us. -
16** -
17** GNU Lesser General Public License Usage -
18** Alternatively, this file may be used under the terms of the GNU Lesser -
19** General Public License version 2.1 as published by the Free Software -
20** Foundation and appearing in the file LICENSE.LGPL included in the -
21** packaging of this file. Please review the following information to -
22** ensure the GNU Lesser General Public License version 2.1 requirements -
23** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -
24** -
25** In addition, as a special exception, Digia gives you certain additional -
26** rights. These rights are described in the Digia Qt LGPL Exception -
27** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -
28** -
29** GNU General Public License Usage -
30** Alternatively, this file may be used under the terms of the GNU -
31** General Public License version 3.0 as published by the Free Software -
32** Foundation and appearing in the file LICENSE.GPL included in the -
33** packaging of this file. Please review the following information to -
34** ensure the GNU General Public License version 3.0 requirements will be -
35** met: http://www.gnu.org/copyleft/gpl.html. -
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{broadcastsender}{Broadcast Sender}, -
93 \l{broadcastreceiver}{Broadcast Receiver}, -
94 \l{multicastsender}{Multicast Sender}, and -
95 \l{multicastreceiver}{Multicast Receiver} examples illustrate how -
96 to use QUdpSocket in applications. -
97 -
98 \sa QTcpSocket -
99*/ -
100 -
101#include "qudpsocket.h" -
102#include "qhostaddress.h" -
103#include "qnetworkinterface.h" -
104#include "qabstractsocket_p.h" -
105 -
106QT_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 -
116class QUdpSocketPrivate : public QAbstractSocketPrivate -
117{ -
118 Q_DECLARE_PUBLIC(QUdpSocket) -
119 -
120 bool doEnsureInitialized(const QHostAddress &bindAddress, quint16 bindPort, -
121 const QHostAddress &remoteAddress); -
122public: -
123 inline bool ensureInitialized(const QHostAddress &bindAddress, quint16 bindPort) -
124 { return doEnsureInitialized(bindAddress, bindPort, QHostAddress()); }
never executed: return doEnsureInitialized(bindAddress, bindPort, QHostAddress());
0
125 -
126 inline bool ensureInitialized(const QHostAddress &remoteAddress) -
127 { return doEnsureInitialized(QHostAddress(), 0, remoteAddress); }
never executed: return doEnsureInitialized(QHostAddress(), 0, remoteAddress);
0
128}; -
129 -
130bool QUdpSocketPrivate::doEnsureInitialized(const QHostAddress &bindAddress, quint16 bindPort, -
131 const QHostAddress &remoteAddress) -
132{ -
133 const QHostAddress *address = &bindAddress;
executed (the execution status of this line is deduced): const QHostAddress *address = &bindAddress;
-
134 QAbstractSocket::NetworkLayerProtocol proto = address->protocol();
executed (the execution status of this line is deduced): QAbstractSocket::NetworkLayerProtocol proto = address->protocol();
-
135 if (proto == QUdpSocket::UnknownNetworkLayerProtocol) {
partially evaluated: proto == QUdpSocket::UnknownNetworkLayerProtocol
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:324697
0-324697
136 address = &remoteAddress;
never executed (the execution status of this line is deduced): address = &remoteAddress;
-
137 proto = address->protocol();
never executed (the execution status of this line is deduced): proto = address->protocol();
-
138 }
never executed: }
0
139 -
140 // now check if the socket engine is initialized and to the right type -
141 if (!socketEngine || !socketEngine->isValid()) {
evaluated: !socketEngine
TRUEFALSE
yes
Evaluation Count:17
yes
Evaluation Count:324680
partially evaluated: !socketEngine->isValid()
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:324680
0-324680
142 resolveProxy(remoteAddress.toString(), bindPort);
executed (the execution status of this line is deduced): resolveProxy(remoteAddress.toString(), bindPort);
-
143 if (!initSocketLayer(address->protocol()))
partially evaluated: !initSocketLayer(address->protocol())
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:17
0-17
144 return false;
never executed: return false;
0
145 }
executed: }
Execution Count:17
17
146 -
147 return true;
executed: return true;
Execution Count:324697
324697
148} -
149 -
150/*! -
151 Creates a QUdpSocket object. -
152 -
153 \a parent is passed to the QObject constructor. -
154 -
155 \sa socketType() -
156*/ -
157QUdpSocket::QUdpSocket(QObject *parent) -
158 : QAbstractSocket(UdpSocket, *new QUdpSocketPrivate, parent) -
159{ -
160 d_func()->isBuffered = false;
executed (the execution status of this line is deduced): d_func()->isBuffered = false;
-
161}
executed: }
Execution Count:321
321
162 -
163/*! -
164 Destroys the socket, closing the connection if necessary. -
165 -
166 \sa close() -
167*/ -
168QUdpSocket::~QUdpSocket() -
169{ -
170} -
171 -
172#ifndef QT_NO_NETWORKINTERFACE -
173 -
174/*! -
175 \since 4.8 -
176 -
177 Joins 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*/ -
190bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress) -
191{ -
192 return joinMulticastGroup(groupAddress, QNetworkInterface());
executed: return joinMulticastGroup(groupAddress, QNetworkInterface());
Execution Count:14
14
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*/ -
204bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress, -
205 const QNetworkInterface &iface) -
206{ -
207 Q_D(QUdpSocket);
executed (the execution status of this line is deduced): QUdpSocketPrivate * const d = d_func();
-
208 QT_CHECK_BOUND("QUdpSocket::joinMulticastGroup()", false);
executed: return (false);
Execution Count:8
executed: }
Execution Count:6
evaluated: !isValid()
TRUEFALSE
yes
Evaluation Count:8
yes
Evaluation Count:6
partially evaluated: 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:6
0-8
209 return d->socketEngine->joinMulticastGroup(groupAddress, iface);
executed: return d->socketEngine->joinMulticastGroup(groupAddress, iface);
Execution Count:6
6
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*/ -
224bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress) -
225{ -
226 return leaveMulticastGroup(groupAddress, QNetworkInterface());
executed: return leaveMulticastGroup(groupAddress, QNetworkInterface());
Execution Count:4
4
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*/ -
238bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress, -
239 const QNetworkInterface &iface) -
240{ -
241 QT_CHECK_BOUND("QUdpSocket::leaveMulticastGroup()", false);
executed: return (false);
Execution Count:2
executed: }
Execution Count:2
evaluated: !isValid()
TRUEFALSE
yes
Evaluation Count:2
yes
Evaluation Count:2
partially evaluated: 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:2
0-2
242 return d_func()->socketEngine->leaveMulticastGroup(groupAddress, iface);
executed: return d_func()->socketEngine->leaveMulticastGroup(groupAddress, iface);
Execution Count:2
2
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*/ -
257QNetworkInterface QUdpSocket::multicastInterface() const -
258{ -
259 Q_D(const QUdpSocket);
executed (the execution status of this line is deduced): const QUdpSocketPrivate * const d = d_func();
-
260 QT_CHECK_BOUND("QUdpSocket::multicastInterface()", QNetworkInterface());
executed: return (QNetworkInterface());
Execution Count:8
executed: }
Execution Count:8
evaluated: !isValid()
TRUEFALSE
yes
Evaluation Count:8
yes
Evaluation Count:8
partially evaluated: 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:8
0-8
261 return d->socketEngine->multicastInterface();
executed: return d->socketEngine->multicastInterface();
Execution Count:8
8
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*/ -
274void QUdpSocket::setMulticastInterface(const QNetworkInterface &iface) -
275{ -
276 Q_D(QUdpSocket);
executed (the execution status of this line is deduced): QUdpSocketPrivate * const d = d_func();
-
277 if (!isValid()) {
evaluated: !isValid()
TRUEFALSE
yes
Evaluation Count:4
yes
Evaluation Count:12
4-12
278 qWarning("QUdpSocket::setMulticastInterface() called on a QUdpSocket when not in QUdpSocket::BoundState");
executed (the execution status of this line is deduced): QMessageLogger("socket/qudpsocket.cpp", 278, __PRETTY_FUNCTION__).warning("QUdpSocket::setMulticastInterface() called on a QUdpSocket when not in QUdpSocket::BoundState");
-
279 return;
executed: return;
Execution Count:4
4
280 } -
281 d->socketEngine->setMulticastInterface(iface);
executed (the execution status of this line is deduced): d->socketEngine->setMulticastInterface(iface);
-
282}
executed: }
Execution Count:12
12
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*/ -
292bool QUdpSocket::hasPendingDatagrams() const -
293{ -
294 QT_CHECK_BOUND("QUdpSocket::hasPendingDatagrams()", false);
never executed: return (false);
executed: }
Execution Count:1984704
partially evaluated: !isValid()
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:1984704
partially evaluated: 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:1984704
0-1984704
295 return d_func()->socketEngine->hasPendingDatagrams();
executed: return d_func()->socketEngine->hasPendingDatagrams();
Execution Count:1984704
1984704
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*/ -
304qint64 QUdpSocket::pendingDatagramSize() const -
305{ -
306 QT_CHECK_BOUND("QUdpSocket::pendingDatagramSize()", -1);
never executed: return (-1);
executed: }
Execution Count:31964
partially evaluated: !isValid()
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:31964
partially evaluated: 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:31964
0-31964
307 return d_func()->socketEngine->pendingDatagramSize();
executed: return d_func()->socketEngine->pendingDatagramSize();
Execution Count:31964
31964
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*/ -
331qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address, -
332 quint16 port) -
333{ -
334 Q_D(QUdpSocket);
executed (the execution status of this line is deduced): QUdpSocketPrivate * const d = d_func();
-
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))
partially evaluated: !d->doEnsureInitialized(QHostAddress::Any, 0, address)
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:324697
0-324697
340 return -1;
never executed: return -1;
0
341 if (state() == UnconnectedState)
evaluated: state() == UnconnectedState
TRUEFALSE
yes
Evaluation Count:17
yes
Evaluation Count:324680
17-324680
342 bind();
executed: bind();
Execution Count:17
17
343 -
344 qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
executed (the execution status of this line is deduced): qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
-
345 d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
executed (the execution status of this line is deduced): d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
-
346 -
347 if (sent >= 0) {
evaluated: sent >= 0
TRUEFALSE
yes
Evaluation Count:324696
yes
Evaluation Count:1
1-324696
348 emit bytesWritten(sent);
executed (the execution status of this line is deduced): bytesWritten(sent);
-
349 } else {
executed: }
Execution Count:324696
324696
350 d->socketError = d->socketEngine->error();
executed (the execution status of this line is deduced): d->socketError = d->socketEngine->error();
-
351 setErrorString(d->socketEngine->errorString());
executed (the execution status of this line is deduced): setErrorString(d->socketEngine->errorString());
-
352 emit error(d->socketError);
executed (the execution status of this line is deduced): error(d->socketError);
-
353 }
executed: }
Execution Count:1
1
354 return sent;
executed: return sent;
Execution Count:324697
324697
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*/ -
381qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *address, -
382 quint16 *port) -
383{ -
384 Q_D(QUdpSocket);
executed (the execution status of this line is deduced): QUdpSocketPrivate * const d = d_func();
-
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);
never executed: return (-1);
executed: }
Execution Count:1313640
partially evaluated: !isValid()
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:1313640
partially evaluated: 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:1313640
0-1313640
390 qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
executed (the execution status of this line is deduced): qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
-
391 d_func()->socketEngine->setReadNotificationEnabled(true);
executed (the execution status of this line is deduced): d_func()->socketEngine->setReadNotificationEnabled(true);
-
392 if (readBytes < 0) {
partially evaluated: readBytes < 0
TRUEFALSE
no
Evaluation Count:0
yes
Evaluation Count:1313640
0-1313640
393 d->socketError = d->socketEngine->error();
never executed (the execution status of this line is deduced): d->socketError = d->socketEngine->error();
-
394 setErrorString(d->socketEngine->errorString());
never executed (the execution status of this line is deduced): setErrorString(d->socketEngine->errorString());
-
395 emit error(d->socketError);
never executed (the execution status of this line is deduced): error(d->socketError);
-
396 }
never executed: }
0
397 return readBytes;
executed: return readBytes;
Execution Count:1313640
1313640
398} -
399#endif // QT_NO_UDPSOCKET -
400 -
401QT_END_NAMESPACE -
402 -
Source codeSwitch to Preprocessed file

Generated by Squish Coco Non-Commercial