我在linux上使用QT 4.8。
我想编写UDP数据报并从特定的网络接口发送它。
我有2个接口:
当两者都启用时,如何选择其中一个网络接口并从中写入数据报?
答案 0 :(得分:5)
简短的回答是bind to *one of the addresses of the eth interface。
Qt有一个非常干净的library for this。但是当我需要弄脏时,我会使用类似ACE C++ library的东西。
无论如何,这里有一些东西可以帮助你入门,但你应该在QtCreator或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 ...
}
答案 1 :(得分:0)
如果您使用的是Qt 5.8或更高版本,则应该能够使用QNetworkDatagram函数之一,如下所示:https://doc.qt.io/qt-5/qnetworkdatagram.html#setInterfaceIndex
void QNetworkDatagram::setInterfaceIndex(uint index)
索引与QNetworkInterface的索引匹配的地方:
// List all of the interfaces
QNetworkInterface netint;
qDebug() << "Network interfaces =" << netint.allInterfaces();
这是一个例子:
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);