Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  1. WLan: IP 192.168.1.77 and mac address
  2. Eth: IP 192.168.1.80 and another mac address

How can I choose one of these Network interfaces and write datagrams from there when both are enabled?

like image 849
Gappa Avatar asked Jun 21 '13 12:06

Gappa


2 Answers

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 ...
}
like image 137
Huy Avatar answered Sep 22 '22 11:09

Huy


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);
like image 35
JimmyJimJames Avatar answered Sep 22 '22 11:09

JimmyJimJames