Qt 4.8
Public Types | Public Functions | List of all members
QUdpSocket Class Reference

The QUdpSocket class provides a UDP socket. More...

#include <qudpsocket.h>

Inheritance diagram for QUdpSocket:
QAbstractSocket QIODevice QObject

Public Types

enum  BindFlag { DefaultForPlatform = 0x0, ShareAddress = 0x1, DontShareAddress = 0x2, ReuseAddressHint = 0x4 }
 This enum describes the different flags you can pass to modify the behavior of QUdpSocket::bind(). More...
 
- Public Types inherited from QAbstractSocket
enum  NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, UnknownNetworkLayerProtocol = -1 }
 This enum describes the network layer protocol values used in Qt. More...
 
enum  SocketError {
  ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError,
  SocketResourceError, SocketTimeoutError, DatagramTooLargeError, NetworkError,
  AddressInUseError, SocketAddressNotAvailableError, UnsupportedSocketOperationError, UnfinishedSocketOperationError,
  ProxyAuthenticationRequiredError, SslHandshakeFailedError, ProxyConnectionRefusedError, ProxyConnectionClosedError,
  ProxyConnectionTimeoutError, ProxyNotFoundError, ProxyProtocolError, UnknownSocketError = -1
}
 This enum describes the socket errors that can occur. More...
 
enum  SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption }
 This enum represents the options that can be set on a socket. More...
 
enum  SocketState {
  UnconnectedState, HostLookupState, ConnectingState, ConnectedState,
  BoundState, ListeningState, ClosingState
}
 This enum describes the different states in which a socket can be. More...
 
enum  SocketType { TcpSocket, UdpSocket, UnknownSocketType = -1 }
 This enum describes the transport layer protocol. More...
 
- Public Types inherited from QIODevice
enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Public Functions

bool bind (const QHostAddress &address, quint16 port)
 Binds this socket to the address address and the port port. More...
 
bool bind (quint16 port=0)
 Binds to QHostAddress:Any on port port. More...
 
bool bind (const QHostAddress &address, quint16 port, BindMode mode)
 Binds to address on port port, using the BindMode mode. More...
 
bool bind (quint16 port, BindMode mode)
 Binds to QHostAddress:Any on port port, using the BindMode mode. More...
 
bool hasPendingDatagrams () const
 Returns true if at least one datagram is waiting to be read; otherwise returns false. More...
 
bool joinMulticastGroup (const QHostAddress &groupAddress)
 Joins the the multicast group specified by groupAddress on the default interface chosen by the operating system. More...
 
bool joinMulticastGroup (const QHostAddress &groupAddress, const QNetworkInterface &iface)
 Joins the multicast group address groupAddress on the interface iface. More...
 
bool leaveMulticastGroup (const QHostAddress &groupAddress)
 Leaves the multicast group specified by groupAddress on the default interface chosen by the operating system. More...
 
bool leaveMulticastGroup (const QHostAddress &groupAddress, const QNetworkInterface &iface)
 Leaves the multicast group specified by groupAddress on the interface iface. More...
 
QNetworkInterface multicastInterface () const
 Returns the interface for the outgoing interface for multicast datagrams. More...
 
qint64 pendingDatagramSize () const
 Returns the size of the first pending UDP datagram. More...
 
 QUdpSocket (QObject *parent=0)
 Creates a QUdpSocket object. More...
 
qint64 readDatagram (char *data, qint64 maxlen, QHostAddress *host=0, quint16 *port=0)
 Receives a datagram no larger than maxSize bytes and stores it in data. More...
 
void setMulticastInterface (const QNetworkInterface &iface)
 Sets the outgoing interface for multicast datagrams to the interface iface. More...
 
qint64 writeDatagram (const char *data, qint64 len, const QHostAddress &host, quint16 port)
 Sends the datagram at data of size size to the host address address at port port. More...
 
qint64 writeDatagram (const QByteArray &datagram, const QHostAddress &host, quint16 port)
 Sends the datagram datagram to the host address host and at port port. More...
 
virtual ~QUdpSocket ()
 Destroys the socket, closing the connection if necessary. More...
 
- Public Functions inherited from QAbstractSocket
void abort ()
 Aborts the current connection and resets the socket. More...
 
bool atEnd () const
 Returns true if no more data is currently available for reading; otherwise returns false. More...
 
qint64 bytesAvailable () const
 Returns the number of incoming bytes that are waiting to be read. More...
 
qint64 bytesToWrite () const
 Returns the number of bytes that are waiting to be written. More...
 
bool canReadLine () const
 Returns true if a line of data can be read from the socket; otherwise returns false. More...
 
void close ()
 Closes the I/O device for the socket, disconnects the socket's connection with the host, closes the socket, and resets the name, address, port number and underlying socket descriptor. More...
 
void connectToHost (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Attempts to make a connection to hostName on the given port. More...
 
void connectToHost (const QHostAddress &address, quint16 port, OpenMode mode=ReadWrite)
 Attempts to make a connection to address on port port. More...
 
void disconnectFromHost ()
 Attempts to close the socket. More...
 
SocketError error () const
 Returns the type of error that last occurred. More...
 
bool flush ()
 This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. More...
 
bool isSequential () const
 Reimplemented Function More...
 
bool isValid () const
 Returns true if the socket is valid and ready for use; otherwise returns false. More...
 
QHostAddress localAddress () const
 Returns the host address of the local socket if available; otherwise returns QHostAddress::Null. More...
 
quint16 localPort () const
 Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0. More...
 
QHostAddress peerAddress () const
 Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null. More...
 
QString peerName () const
 Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called. More...
 
quint16 peerPort () const
 Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0. More...
 
QNetworkProxy proxy () const
 Returns the network proxy for this socket. More...
 
 QAbstractSocket (SocketType socketType, QObject *parent)
 Creates a new abstract socket of type socketType. More...
 
qint64 readBufferSize () const
 Returns the size of the internal read buffer. More...
 
void setProxy (const QNetworkProxy &networkProxy)
 Sets the explicit network proxy for this socket to networkProxy. More...
 
void setReadBufferSize (qint64 size)
 Sets the size of QAbstractSocket's internal read buffer to be size bytes. More...
 
bool setSocketDescriptor (int socketDescriptor, SocketState state=ConnectedState, OpenMode openMode=ReadWrite)
 Initializes QAbstractSocket with the native socket descriptor socketDescriptor. More...
 
void setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value)
 Sets the given option to the value described by value. More...
 
int socketDescriptor () const
 Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1. More...
 
QVariant socketOption (QAbstractSocket::SocketOption option)
 Returns the value of the option option. More...
 
SocketType socketType () const
 Returns the socket type (TCP, UDP, or other). More...
 
SocketState state () const
 Returns the state of the socket. More...
 
bool waitForBytesWritten (int msecs=30000)
 Reimplemented Function More...
 
bool waitForConnected (int msecs=30000)
 Waits until the socket is connected, up to msecs milliseconds. More...
 
bool waitForDisconnected (int msecs=30000)
 Waits until the socket has disconnected, up to msecs milliseconds. More...
 
bool waitForReadyRead (int msecs=30000)
 This function blocks until new data is available for reading and the QIODevice::readyRead() signal has been emitted. More...
 
virtual ~QAbstractSocket ()
 Destroys the socket. More...
 
- Public Functions inherited from QIODevice
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
virtual bool open (OpenMode mode)
 Opens the device and sets its OpenMode to mode. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
qint64 readLine (char *data, qint64 maxlen)
 This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
virtual bool seek (qint64 pos)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Signals inherited from QAbstractSocket
void connected ()
 This signal is emitted after connectToHost() has been called and a connection has been successfully established. More...
 
void disconnected ()
 This signal is emitted when the socket has been disconnected. More...
 
void error (QAbstractSocket::SocketError)
 This signal is emitted after an error occurred. More...
 
void hostFound ()
 This signal is emitted after connectToHost() has been called and the host lookup has succeeded. More...
 
void proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator)
 
void stateChanged (QAbstractSocket::SocketState)
 This signal is emitted whenever QAbstractSocket's state changes. More...
 
- Signals inherited from QIODevice
void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Slots inherited from QAbstractSocket
void connectToHostImplementation (const QString &hostName, quint16 port, OpenMode mode=ReadWrite)
 Contains the implementation of connectToHost(). More...
 
void disconnectFromHostImplementation ()
 Contains the implementation of disconnectFromHost(). More...
 
- Protected Functions inherited from QAbstractSocket
 QAbstractSocket (SocketType socketType, QAbstractSocketPrivate &dd, QObject *parent=0)
 Constructs a new abstract socket of type socketType. More...
 
qint64 readData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
qint64 readLineData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
void setLocalAddress (const QHostAddress &address)
 Sets the address on the local side of a connection to address. More...
 
void setLocalPort (quint16 port)
 Sets the port on the local side of a connection to port. More...
 
void setPeerAddress (const QHostAddress &address)
 Sets the address of the remote side of the connection to address. More...
 
void setPeerName (const QString &name)
 Sets the host name of the remote peer to name. More...
 
void setPeerPort (quint16 port)
 Sets the port of the remote side of the connection to port. More...
 
void setSocketError (SocketError socketError)
 Sets the type of error that last occurred to socketError. More...
 
void setSocketState (SocketState state)
 Sets the state of the socket to state. More...
 
qint64 writeData (const char *data, qint64 len)
 Reimplemented Function More...
 
- Protected Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QUdpSocket class provides a UDP socket.

Note
This class or function is reentrant.
Attention
Module: QtNetwork

UDP (User Datagram Protocol) is a lightweight, unreliable, datagram-oriented, connectionless protocol. It can be used when reliability isn't important. QUdpSocket is a subclass of QAbstractSocket that allows you to send and receive UDP datagrams.

The most common way to use this class is to bind to an address and port using bind(), then call writeDatagram() and readDatagram() to transfer data. If you want to use the standard QIODevice functions read(), readLine(), write(), etc., you must first connect the socket directly to a peer by calling connectToHost().

The socket emits the bytesWritten() signal every time a datagram is written to the network. If you just want to send datagrams, you don't need to call bind().

The readyRead() signal is emitted whenever datagrams arrive. In that case, hasPendingDatagrams() returns true. Call pendingDatagramSize() to obtain the size of the first pending datagram, and readDatagram() to read it.

Note
An incoming datagram should be read when you receive the readyRead() signal, otherwise this signal will not be emitted for the next datagram.

Example:

void Server::initSocket()
{
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 7755);
connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
}
void Server::readPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
processTheDatagram(datagram);
}
}

QUdpSocket also supports UDP multicast. Use joinMulticastGroup() and leaveMulticastGroup() to control group membership, and QAbstractSocket::MulticastTtlOption and QAbstractSocket::MulticastLoopbackOption to set the TTL and loopback socket options. Use setMulticastInterface() to control the outgoing interface for multicast datagrams, and multicastInterface() to query it.

With QUdpSocket, you can also establish a virtual connection to a UDP server using connectToHost() and then use read() and write() to exchange datagrams without specifying the receiver for each datagram.

The Broadcast Sender, Broadcast Receiver, Multicast Sender, and Multicast Receiver examples illustrate how to use QUdpSocket in applications.

Symbian Platform Security Requirements

On Symbian, processes which use this class must have the NetworkServices platform security capability. If the client process lacks this capability, operations will result in a panic.

Platform security capabilities are added via the TARGET.CAPABILITY qmake variable.

See also
QTcpSocket

Definition at line 59 of file qudpsocket.h.

Enumerations

◆ BindFlag

This enum describes the different flags you can pass to modify the behavior of QUdpSocket::bind().

Since
4.1
Note
On Symbian OS bind flags behaviour depends on process capabilties. If process has NetworkControl capability, the bind attempt with ReuseAddressHint will always succeed even if the address and port is already bound by another socket with any flags. If process does not have NetworkControl capability, the bind attempt to address and port already bound by another socket will always fail.
  • ShareAddress Allow other services to bind to the same address and port. This is useful when multiple processes share the load of a single service by listening to the same address and port (e.g., a web server with several pre-forked listeners can greatly improve response time). However, because any service is allowed to rebind, this option is subject to certain security considerations. Note that by combining this option with ReuseAddressHint, you will also allow your service to rebind an existing shared address. On Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows, this option is ignored.
  • DontShareAddress Bind the address and port exclusively, so that no other services are allowed to rebind. By passing this option to QUdpSocket::bind(), you are guaranteed that on successs, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass ReuseAddressHint. This option provides more security than ShareAddress, but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and Mac OS X, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.
  • ReuseAddressHint Provides a hint to QUdpSocket that it should try to rebind the service even if the address and port are already bound by another socket. On Windows, this is equivalent to the SO_REUSEADDR socket option. On Unix, this option is ignored.
  • DefaultForPlatform The default option for the current platform. On Unix and Mac OS X, this is equivalent to (DontShareAddress
    • ReuseAddressHint), and on Windows, its equivalent to ShareAddress.
Enumerator
DefaultForPlatform 
ShareAddress 
DontShareAddress 
ReuseAddressHint 

Definition at line 63 of file qudpsocket.h.

Constructors and Destructors

◆ QUdpSocket()

QUdpSocket::QUdpSocket ( QObject parent = 0)
explicit

Creates a QUdpSocket object.

parent is passed to the QObject constructor.

See also
socketType()

Definition at line 227 of file qudpsocket.cpp.

229 {
230  d_func()->isBuffered = false;
231 }
QAbstractSocket(SocketType socketType, QObject *parent)
Creates a new abstract socket of type socketType.

◆ ~QUdpSocket()

QUdpSocket::~QUdpSocket ( )
virtual

Destroys the socket, closing the connection if necessary.

See also
close()

Definition at line 238 of file qudpsocket.cpp.

239 {
240 }

Functions

◆ bind() [1/4]

bool QUdpSocket::bind ( const QHostAddress address,
quint16  port 
)

Binds this socket to the address address and the port port.

When bound, the signal readyRead() is emitted whenever a UDP datagram arrives on the specified address and port. This function is useful to write UDP servers.

On success, the functions returns true and the socket enters BoundState; otherwise it returns false.

The socket is bound using the DefaultForPlatform BindMode.

See also
readDatagram()

Definition at line 255 of file qudpsocket.cpp.

Referenced by bind(), and QSocks5SocketEngine::bind().

256 {
257  Q_D(QUdpSocket);
258  if (!d->ensureInitialized(address, port))
259  return false;
260 
261  bool result = d_func()->socketEngine->bind(address, port);
262  d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
263 
264  if (!result) {
265  d->socketError = d_func()->socketEngine->error();
266  setErrorString(d_func()->socketEngine->errorString());
267  emit error(d_func()->socketError);
268  return false;
269  }
270 
271  d->state = BoundState;
272  d->localAddress = d->socketEngine->localAddress();
273  d->localPort = d->socketEngine->localPort();
274 
275  emit stateChanged(d_func()->state);
276  d_func()->socketEngine->setReadNotificationEnabled(true);
277  return true;
278 }
double d
Definition: qnumeric_p.h:62
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
#define Q_D(Class)
Definition: qglobal.h:2482
#define emit
Definition: qobjectdefs.h:76
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
SocketError error() const
Returns the type of error that last occurred.
SocketState state() const
Returns the state of the socket.

◆ bind() [2/4]

bool QUdpSocket::bind ( quint16  port = 0)

Binds to QHostAddress:Any on port port.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 337 of file qudpsocket.cpp.

338 {
339  return bind(QHostAddress::Any, port);
340 }
bool bind(const QHostAddress &address, quint16 port)
Binds this socket to the address address and the port port.
Definition: qudpsocket.cpp:255

◆ bind() [3/4]

bool QUdpSocket::bind ( const QHostAddress address,
quint16  port,
BindMode  mode 
)

Binds to address on port port, using the BindMode mode.

Since
4.1 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 289 of file qudpsocket.cpp.

290 {
291  Q_D(QUdpSocket);
292  if (!d->ensureInitialized(address, port))
293  return false;
294 
295 #ifdef Q_OS_UNIX
296  if ((mode & ShareAddress) || (mode & ReuseAddressHint))
297  d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
298  else
299  d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
300 #endif
301 #ifdef Q_OS_WIN
302  if (mode & ReuseAddressHint)
303  d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
304  else
305  d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
306  if (mode & DontShareAddress)
307  d->socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 1);
308  else
309  d->socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 0);
310 #endif
311  bool result = d_func()->socketEngine->bind(address, port);
312  d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
313 
314  if (!result) {
315  d->socketError = d_func()->socketEngine->error();
316  setErrorString(d_func()->socketEngine->errorString());
317  emit error(d_func()->socketError);
318  return false;
319  }
320 
321  d->state = BoundState;
322  d->localAddress = d->socketEngine->localAddress();
323  d->localPort = d->socketEngine->localPort();
324 
325  emit stateChanged(d_func()->state);
326  d_func()->socketEngine->setReadNotificationEnabled(true);
327  return true;
328 }
double d
Definition: qnumeric_p.h:62
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
#define Q_D(Class)
Definition: qglobal.h:2482
#define emit
Definition: qobjectdefs.h:76
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
void stateChanged(QAbstractSocket::SocketState)
This signal is emitted whenever QAbstractSocket&#39;s state changes.
SocketError error() const
Returns the type of error that last occurred.
SocketState state() const
Returns the state of the socket.

◆ bind() [4/4]

bool QUdpSocket::bind ( quint16  port,
BindMode  mode 
)

Binds to QHostAddress:Any on port port, using the BindMode mode.

Since
4.1 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 351 of file qudpsocket.cpp.

352 {
353  return bind(QHostAddress::Any, port, mode);
354 }
bool bind(const QHostAddress &address, quint16 port)
Binds this socket to the address address and the port port.
Definition: qudpsocket.cpp:255

◆ hasPendingDatagrams()

bool QUdpSocket::hasPendingDatagrams ( ) const

Returns true if at least one datagram is waiting to be read; otherwise returns false.

See also
pendingDatagramSize(), readDatagram()

Definition at line 490 of file qudpsocket.cpp.

491 {
492  QT_CHECK_BOUND("QUdpSocket::hasPendingDatagrams()", false);
493  return d_func()->socketEngine->hasPendingDatagrams();
494 }
#define QT_CHECK_BOUND(function, a)
Definition: qudpsocket.cpp:171

◆ joinMulticastGroup() [1/2]

bool QUdpSocket::joinMulticastGroup ( const QHostAddress groupAddress)

Joins the the multicast group specified by groupAddress on the default interface chosen by the operating system.

Since
4.8

The socket must be in BoundState, otherwise an error occurs.

This function returns true if successful; otherwise it returns false and sets the socket error accordingly.

See also
leaveMulticastGroup()

Definition at line 373 of file qudpsocket.cpp.

374 {
375  return joinMulticastGroup(groupAddress, QNetworkInterface());
376 }
bool joinMulticastGroup(const QHostAddress &groupAddress)
Joins the the multicast group specified by groupAddress on the default interface chosen by the operat...
Definition: qudpsocket.cpp:373
The QNetworkInterface class provides a listing of the host&#39;s IP addresses and network interfaces...

◆ joinMulticastGroup() [2/2]

bool QUdpSocket::joinMulticastGroup ( const QHostAddress groupAddress,
const QNetworkInterface iface 
)

Joins the multicast group address groupAddress on the interface iface.

Since
4.8 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
See also
leaveMulticastGroup()

Definition at line 390 of file qudpsocket.cpp.

392 {
393  Q_D(QUdpSocket);
394  QT_CHECK_BOUND("QUdpSocket::joinMulticastGroup()", false);
395  return d->socketEngine->joinMulticastGroup(groupAddress, iface);
396 }
double d
Definition: qnumeric_p.h:62
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
#define Q_D(Class)
Definition: qglobal.h:2482
#define QT_CHECK_BOUND(function, a)
Definition: qudpsocket.cpp:171

◆ leaveMulticastGroup() [1/2]

bool QUdpSocket::leaveMulticastGroup ( const QHostAddress groupAddress)

Leaves the multicast group specified by groupAddress on the default interface chosen by the operating system.

Since
4.8

The socket must be in BoundState, otherwise an error occurs.

This function returns true if successful; otherwise it returns false and sets the socket error accordingly.

See also
joinMulticastGroup()

Definition at line 413 of file qudpsocket.cpp.

414 {
415  return leaveMulticastGroup(groupAddress, QNetworkInterface());
416 }
bool leaveMulticastGroup(const QHostAddress &groupAddress)
Leaves the multicast group specified by groupAddress on the default interface chosen by the operating...
Definition: qudpsocket.cpp:413
The QNetworkInterface class provides a listing of the host&#39;s IP addresses and network interfaces...

◆ leaveMulticastGroup() [2/2]

bool QUdpSocket::leaveMulticastGroup ( const QHostAddress groupAddress,
const QNetworkInterface iface 
)

Leaves the multicast group specified by groupAddress on the interface iface.

Since
4.8 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
See also
joinMulticastGroup()

Definition at line 430 of file qudpsocket.cpp.

432 {
433  QT_CHECK_BOUND("QUdpSocket::leaveMulticastGroup()", false);
434  return d_func()->socketEngine->leaveMulticastGroup(groupAddress, iface);
435 }
#define QT_CHECK_BOUND(function, a)
Definition: qudpsocket.cpp:171

◆ multicastInterface()

QNetworkInterface QUdpSocket::multicastInterface ( ) const

Returns the interface for the outgoing interface for multicast datagrams.

Since
4.8

This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. If no interface has been previously set, this function returns an invalid QNetworkInterface. The socket must be in BoundState, otherwise an invalid QNetworkInterface is returned.

See also
setMulticastInterface()

Definition at line 452 of file qudpsocket.cpp.

453 {
454  Q_D(const QUdpSocket);
455  QT_CHECK_BOUND("QUdpSocket::multicastInterface()", QNetworkInterface());
456  return d->socketEngine->multicastInterface();
457 }
double d
Definition: qnumeric_p.h:62
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
#define Q_D(Class)
Definition: qglobal.h:2482
#define QT_CHECK_BOUND(function, a)
Definition: qudpsocket.cpp:171
The QNetworkInterface class provides a listing of the host&#39;s IP addresses and network interfaces...

◆ pendingDatagramSize()

qint64 QUdpSocket::pendingDatagramSize ( ) const

Returns the size of the first pending UDP datagram.

If there is no datagram available, this function returns -1.

See also
hasPendingDatagrams(), readDatagram()

Definition at line 502 of file qudpsocket.cpp.

503 {
504  QT_CHECK_BOUND("QUdpSocket::pendingDatagramSize()", -1);
505  return d_func()->socketEngine->pendingDatagramSize();
506 }
#define QT_CHECK_BOUND(function, a)
Definition: qudpsocket.cpp:171

◆ readDatagram()

qint64 QUdpSocket::readDatagram ( char *  data,
qint64  maxSize,
QHostAddress address = 0,
quint16 port = 0 
)

Receives a datagram no larger than maxSize bytes and stores it in data.

The sender's host address and port is stored in address and *port (unless the pointers are 0).

Returns the size of the datagram on success; otherwise returns -1.

If maxSize is too small, the rest of the datagram will be lost. To avoid loss of data, call pendingDatagramSize() to determine the size of the pending datagram before attempting to read it. If maxSize is 0, the datagram will be discarded.

See also
writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()

Definition at line 583 of file qudpsocket.cpp.

Referenced by QSocks5SocketEngine::bind().

585 {
586  Q_D(QUdpSocket);
587 
588 #if defined QUDPSOCKET_DEBUG
589  qDebug("QUdpSocket::readDatagram(%p, %llu, %p, %p)", data, maxSize, address, port);
590 #endif
591  QT_CHECK_BOUND("QUdpSocket::readDatagram()", -1);
592  qint64 readBytes = d->socketEngine->readDatagram(data, maxSize, address, port);
593  d_func()->socketEngine->setReadNotificationEnabled(true);
594  if (readBytes < 0) {
595  d->socketError = d->socketEngine->error();
596  setErrorString(d->socketEngine->errorString());
597  emit error(d->socketError);
598  }
599  return readBytes;
600 }
double d
Definition: qnumeric_p.h:62
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
#define Q_D(Class)
Definition: qglobal.h:2482
#define QT_CHECK_BOUND(function, a)
Definition: qudpsocket.cpp:171
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
static const char * data(const QByteArray &arr)
__int64 qint64
Definition: qglobal.h:942
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
SocketError error() const
Returns the type of error that last occurred.

◆ setMulticastInterface()

void QUdpSocket::setMulticastInterface ( const QNetworkInterface iface)

Sets the outgoing interface for multicast datagrams to the interface iface.

Since
4.8

This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. The socket must be in BoundState, otherwise this function does nothing.

See also
multicastInterface(), joinMulticastGroup(), leaveMulticastGroup()

Definition at line 472 of file qudpsocket.cpp.

473 {
474  Q_D(QUdpSocket);
475  if (!isValid()) {
476  qWarning("QUdpSocket::setMulticastInterface() called on a QUdpSocket when not in QUdpSocket::BoundState");
477  return;
478  }
479  d->socketEngine->setMulticastInterface(iface);
480 }
double d
Definition: qnumeric_p.h:62
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
bool isValid() const
Returns true if the socket is valid and ready for use; otherwise returns false.

◆ writeDatagram() [1/2]

qint64 QUdpSocket::writeDatagram ( const char *  data,
qint64  size,
const QHostAddress address,
quint16  port 
)

Sends the datagram at data of size size to the host address address at port port.

Returns the number of bytes sent on success; otherwise returns -1.

Datagrams are always written as one block. The maximum size of a datagram is highly platform-dependent, but can be as low as 8192 bytes. If the datagram is too large, this function will return -1 and error() will return DatagramTooLargeError.

Sending datagrams larger than 512 bytes is in general disadvised, as even if they are sent successfully, they are likely to be fragmented by the IP layer before arriving at their final destination.

Warning
In S60 5.0 and earlier versions, the writeDatagram return value is not reliable for large datagrams.
Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.
See also
readDatagram(), write()

Definition at line 532 of file qudpsocket.cpp.

534 {
535  Q_D(QUdpSocket);
536 #if defined QUDPSOCKET_DEBUG
537  qDebug("QUdpSocket::writeDatagram(%p, %llu, \"%s\", %i)", data, size,
538  address.toString().toLatin1().constData(), port);
539 #endif
540  if (!d->ensureInitialized(address))
541  return -1;
542 
543  qint64 sent = d->socketEngine->writeDatagram(data, size, address, port);
544  d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
545 
546  if (sent >= 0) {
547  emit bytesWritten(sent);
548  } else {
549  d->socketError = d->socketEngine->error();
550  setErrorString(d->socketEngine->errorString());
551  emit error(d->socketError);
552  }
553  return sent;
554 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
The QUdpSocket class provides a UDP socket.
Definition: qudpsocket.h:59
void bytesWritten(qint64 bytes)
This signal is emitted every time a payload of data has been written to the device.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
static const char * data(const QByteArray &arr)
QString toString() const
Returns the address as a string.
QByteArray toLatin1() const Q_REQUIRED_RESULT
Returns a Latin-1 representation of the string as a QByteArray.
Definition: qstring.cpp:3993
__int64 qint64
Definition: qglobal.h:942
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
SocketError error() const
Returns the type of error that last occurred.

◆ writeDatagram() [2/2]

qint64 QUdpSocket::writeDatagram ( const QByteArray datagram,
const QHostAddress host,
quint16  port 
)
inline

Sends the datagram datagram to the host address host and at port port.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 96 of file qudpsocket.h.

97  { return writeDatagram(datagram.constData(), datagram.size(), host, port); }
qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port)
Sends the datagram at data of size size to the host address address at port port. ...
Definition: qudpsocket.cpp:532
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402

The documentation for this class was generated from the following files: