QList<QNetworkInterface> ifaceList=QNetworkInterface::allInterfaces();
for(int i=0;i<ifaceList.count();i++)
{
QNetworkInterface var=ifaceList.at(i);
ui->comboBox_NIC->addItem(var.humanReadableName());
}
效果图:
初始化时执行了此函数,当网卡发生变化后再次选择网卡可能会导致程序崩溃。所以当网卡发生变化时 需要更新一下。
使用setMulticastInterface(&face)函数来指定网卡
输入IP,绑定输入IP指定网卡,也可以通过选择网卡,直接绑定网卡文章来源:https://www.toymoban.com/news/detail-517991.html
int NIC_choice = ui->comboBox_NIC->currentIndex();
int local_port = ui->lineEdit_port->text().toUInt();
QList<QNetworkInterface> netList = QNetworkInterface::allInterfaces();
int flag = 1;
QList<QNetworkAddressEntry> entryList = netList[NIC_choice].addressEntries();
dst_ip = QHostAddress(ui->lineEdit_IP_dst->text());
dst_port = ui->lineEdit_port_dst->text().toUInt();
foreach(QNetworkAddressEntry entry,entryList)
{
qDebug() << QHostAddress(entry.ip()) << endl;
if(QHostAddress(entry.ip()) == QHostAddress(ui->lineEdit_IP->text()))
{
flag = 0;
if(udpSocket_net == NULL)
{
udpSocket_net = new QUdpSocket;
if(true == udpSocket_net->bind(QHostAddress::AnyIPv4, local_port, QAbstractSocket::ShareAddress))// 第一步:绑定
{
udpSocket_net->setMulticastInterface(netList[NIC_choice]);// 第二步:指定网卡
udpSocket_net->joinMulticastGroup(dst_ip, netList[NIC_choice]);
udpSocket_net->setSocketOption( udpSocket_net->MulticastLoopbackOption,1);
udpSocket_net->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption,1024*1024*8);
connect(udpSocket_net,SIGNAL(readyRead()),this,SLOT(Device_info_readyRead()));
ui->pushButton_connect_net->setText("关闭网络");
}
else
{
QMessageBox::critical(this, tr("打开失败"), tr("端口占用"), QMessageBox::Ok);
udpSocket_net = NULL;
}
}
}
}
if(flag)
{
QMessageBox::critical(this, tr("打开失败"), tr("IP错误"), QMessageBox::Ok);
}
文章来源地址https://www.toymoban.com/news/detail-517991.html
到了这里,关于QT读取网卡列表多网卡绑定组播网卡的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!