QHostAddress(“192.168.1.5”)这种指定ip,在接收端无法接收
只能使用QHostAddress(“255.255.255.255”)或者QHostAddress::Broadcast,我在测试发送QHostAddress::LocalHost也无法在本机接收
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
#include <QHostInfo>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//本地主机名
QString hostName = QHostInfo::localHostName();
//本机IP地址
QHostInfo hostInfo = QHostInfo::fromName(hostName);
//IP地址列表
QList<QHostAddress> addrList = hostInfo.addresses();
for(int i=0;i<addrList.count();i++)
{
QHostAddress host = addrList.at(i);
if(QAbstractSocket::IPv4Protocol == host.protocol())
{
QString ip = host.toString();
ui->comboBox->addItem(ip);
}
}
udpSocket=new QUdpSocket(this);
if(udpSocket->bind(5050))
qDebug()<<"绑定成功";
connect(udpSocket,&QUdpSocket::readyRead,this,&MainWindow::showtext);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_Button_send_clicked()
{
mystruct test;
test.testport=5050;
strcpy(test.text,"你好");
test.size=sizeof (test.text);
// udpSocket->writeDatagram((char *)&test,sizeof(test),QHostAddress(ui->comboBox->currentText()),5050);
udpSocket->writeDatagram((char *)&test,sizeof(test),QHostAddress("127.0.0.1"),5050);
}
void MainWindow::showtext()
{
mystruct s;
while (udpSocket->hasPendingDatagrams())
{
udpSocket->readDatagram((char*)&s,sizeof (s));
ui->text_receive->appendPlainText(s.text);
qDebug()<<"接收成功";
}
}
因为发送端指定IP后,数据会自动发送到接收端对应的IP及端口,所以接收端不需要设置IP。