如何通过QT中的特定网络接口写入数据报?

Gap*_*ppa 4 sockets qt udp network-programming

我在linux上使用QT 4.8.

我想编写UDP数据报并从特定的网络接口发送它.

我有2个接口:

  1. WLan:IP 192.168.1.77和mac地址
  2. Eth:IP 192.168.1.80和另一个mac地址

当两者都启用时,如何选择其中一个网络接口并从中写入数据报?

Huy*_*Huy 5

简短的回答是,绑定到eth接口的*地址之一.

Qt有一个非常干净的.但是当我需要弄脏时,我会使用类似ACE C++库的东西.

无论如何,这里有一些东西可以让你入门,但你应该在QtCreator或谷歌中查看更具体的例子:

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 ...
}
Run Code Online (Sandbox Code Playgroud)