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指定网卡,也可以通过选择网卡,直接绑定网卡
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://blog.csdn.net/qq_30727593/article/details/127441711
版权归原作者 Acnidouwo 所有, 如有侵权,请联系我们删除。
版权归原作者 Acnidouwo 所有, 如有侵权,请联系我们删除。