【发布时间】:2013-06-18 14:36:07
【问题描述】:
我在 linux 上使用 QT 4.8。
我想编写 UDP 数据报并从特定网络接口发送。
我有 2 个接口:
- WLAN:IP 192.168.1.77 和 mac 地址
- Eth:IP 192.168.1.80 和另一个 mac 地址
当两者都启用时,我如何选择其中一个网络接口并从那里写入数据报?
【问题讨论】:
标签: qt sockets network-programming udp
我在 linux 上使用 QT 4.8。
我想编写 UDP 数据报并从特定网络接口发送。
我有 2 个接口:
当两者都启用时,我如何选择其中一个网络接口并从那里写入数据报?
【问题讨论】:
标签: qt sockets network-programming udp
如果您使用的是 Qt 5.8 或更新版本,您应该能够使用其中一个 QNetworkDatagram 函数,如下所示:https://doc.qt.io/qt-5/qnetworkdatagram.html#setInterfaceIndex
void QNetworkDatagram::setInterfaceIndex(uint index)
其中 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);
【讨论】:
简短的回答是,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 ...
}
【讨论】: