How to write a datagram through a specific network interface in QT?

I am using QT 4.8 for linux.

I would like to write UDP datagrams and send it from a specific network interface.

I have 2 interfaces:

  • Wlan: IP 192.168.1.77 and mac address
  • Eth: IP 192.168.1.80 and another mac address

How can I select one of these network interfaces and record datagrams where they are included?

+4
source share
2 answers

Short answer: bind to * one of the addresses of this interface .

Qt has a pretty surprisingly clean library for this . But when I need to fall dirty, I will use something like ACE C ++ library .

In any case, here is what you need, but you should study more specific examples in QtCreator or google :

QUdpSocket socket; // I am using the eth interface that 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 ... } 
+5
source

If you are using Qt 5.8 or later, you can use one of the QNetworkDatagram features, as shown here: https://doc.qt.io/qt-5/qnetworkdatagram.html#setInterfaceIndex

 void QNetworkDatagram::setInterfaceIndex(uint index) 

Where the index matches the index from QNetworkInterface:

 // List all of the interfaces QNetworkInterface netint; qDebug() << "Network interfaces =" << netint.allInterfaces(); 

Here is 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); 
0
source

Source: https://habr.com/ru/post/1487469/


All Articles