I try to write a QUdpsocket for read and write on braodcast address. following code work in windows with Qt5 library but don't work on my CentOs with Qt4.6, (i haven't any error in CentOs just don't read anything)
configure qudpsocket
iface = "";
if(nf.name() == iface || iface.isNull() || iface.isEmpty())
{
{
if(na.broadcast().toString() != "") {
send_to = na.broadcast().toIPv4Address();
bind_to = na.ip().toIPv4Address();
hostname = na.ip().toString();
if (verbose)
qDebug("using address=%s broadcast=%s",
na.ip().toString().toLocal8Bit().data(), na.broadcast().toString().toLocal8Bit().data());
break;
}
}
}
}
if(hostname != "") break;
}
if(bind_to)
{
broadcast.setAddress(send_to);
#ifdef Q_OS_WIN
#elif defined(Q_OS_LINUX)
QHostAddress address
(send_to
);
// dont work on centos Qt 4.7 #endif
if(!udpsock.
bind(address, port_nbr,
QUdpSocket::ShareAddress qFatal("bind udp");
if(verbose)
qDebug() << "configured, hostname=" << hostname;
}
iface = "";
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
foreach (QNetworkInterface nf, ifaces) {
if(nf.name() == iface || iface.isNull() || iface.isEmpty())
{
if(nf.flags() & QNetworkInterface::CanBroadcast)
{
foreach (QNetworkAddressEntry na, nf.addressEntries()) {
if(na.broadcast().toString() != "") {
send_to = na.broadcast().toIPv4Address();
bind_to = na.ip().toIPv4Address();
hostname = na.ip().toString();
if (verbose)
qDebug("using address=%s broadcast=%s",
na.ip().toString().toLocal8Bit().data(), na.broadcast().toString().toLocal8Bit().data());
break;
}
}
}
}
if(hostname != "") break;
}
if(bind_to)
{
broadcast.setAddress(send_to);
#ifdef Q_OS_WIN
QHostAddress address(bind_to);
#elif defined(Q_OS_LINUX)
QHostAddress address(send_to); // dont work on centos Qt 4.7
#endif
if(!udpsock.bind(address, port_nbr, QUdpSocket::ShareAddress
| QUdpSocket::ReuseAddressHint))
qFatal("bind udp");
if(verbose)
qDebug() << "configured, hostname=" << hostname;
}
To copy to clipboard, switch view to plain text mode
loop for listening
int handleUdp() {
if(!udpsock.hasPendingDatagrams()) return -1;
char data[1024];
int rsize = udpsock.readDatagram(data, 1024, &peerAddress);
if(rsize <= 0) return -1;
.....
return 0;
}
while(!terminated) {
...
if(udpsock.waitForReadyRead(2000))
handleUdp();
...
// end of each loop broadcast data
udpsock.writeDatagram(data(), broadcast, port_nbr)
}
int handleUdp() {
if(!udpsock.hasPendingDatagrams()) return -1;
char data[1024];
QHostAddress peerAddress;
int rsize = udpsock.readDatagram(data, 1024, &peerAddress);
if(rsize <= 0) return -1;
.....
return 0;
}
while(!terminated) {
...
if(udpsock.waitForReadyRead(2000))
handleUdp();
...
// end of each loop broadcast data
udpsock.writeDatagram(data(), broadcast, port_nbr)
}
To copy to clipboard, switch view to plain text mode
this is debug information:
using address=123.123.1.14 broadcast=123.255.255.255
configured, hostname=123.123.1.14
Bookmarks