I'm using QT 4.8 on linux.
I would like to write UDP datagrams and send it from a specific network interface.
I have 2 interfaces:
How can I choose one of these Network interfaces and write datagrams from there when both are enabled?
The short answer is, bind to *one of the addresses of the eth interface.
Qt has a pretty awesomely clean library for this. But when I need to get down a dirty, I'll use something like the ACE C++ library.
Anyway, here's something to get you started, but you should look into more concrete examples in QtCreator or google:
QUdpSocket socket;
// I am using the eth interface that's associated
// with IP 192.168.1.77
//
// Note that I'm using a "random" (ephemeral) port by passing 0
if(socket.bind(QHostAddress("192.168.1.77"), 0))
{
// Send it out to some IP (192.168.1.1) and port (45354).
qint64 bytesSent = socket.writeDatagram(QByteArray("Hello World!"),
QHostAddress("192.168.1.1"),
45354);
// ... etc ...
}
If you are using Qt 5.8 or newer, you should be able to use one of the QNetworkDatagram functions, as shown here: https://doc.qt.io/qt-5/qnetworkdatagram.html#setInterfaceIndex
void QNetworkDatagram::setInterfaceIndex(uint index)
Where index matches the index from QNetworkInterface:
// List all of the interfaces
QNetworkInterface netint;
qDebug() << "Network interfaces =" << netint.allInterfaces();
Here's an example:
QByteArray data;
data.fill('c', 20); // stuff some data in here
QNetworkDatagram netDatagram(data, QHostAddress("239.0.0.1"), 54002);
netDatagram.setInterfaceIndex(2); // whatever index 2 is on your system
udpSocket->writeDatagram(netDatagram);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With