原文:https://blog.csdn.net/uyy203/article/details/51047095
定义
udpSocket = new QUdpSocket(this);
QByteArray datagram = "http://blog.csdn.net/uyy203";
udpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 8686);
udpSocket->bind(QHostAddress("192.168.191.10"), 8686);
UDP客户端广播
QUdpSocket *udpsocket1 = new QUdpSocket(this);
QByteArray datagram = "http://blog.csdn.net/uyy203"; udpsocket1->writeDatagram(datagram.data(),datagram.size(), QHostAddress::Broadcast,ui->spinBox->text().toInt());
UDP客户端发送到指定IP
QUdpSocket *udpsocket1 = new QUdpSocket(this);
QByteArray datagram = "http://blog.csdn.net/uyy203"; udpsocket1->writeDatagram(datagram.data(),datagram.size(), QHostAddress("192.168.191.10"),ui->spinBox->text().toInt());
收数据
connect(udpsocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
while (udpsocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpsocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpsocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
qDebug()<<datagram.data()<<datagram.size()<<senderPort<<sender.toString(); //processTheDatagram(datagram);
}
获取本地IP
QString getLocalIP(){
QList<QHostAddress> list = QNetworkInterface::allAddresses();
foreach (QHostAddress address, list)
{
if(address.protocol() == QAbstractSocket::IPv4Protocol)
return address.toString();
}
return "";
}
本地IP和端口绑定
bool Connect(QString IP,QString port)
{
udpReceiverSocket->close();
udpSenderSocket->close();
bindReceiverFlag=bindSenderFlag=false;
bindReceiverFlag=udpReceiverSocket->bind(QHostAddress(IP),port.toInt());
bindSenderFlag=udpSenderSocket->bind(port.toInt());
if(bindReceiverFlag&&bindSenderFlag)
return true;
else
return false;
}
接收数据,获取数据长度,发送方IP,发送方端口
udpReceiverSocket->readDatagram(datagram.data(), datagram.size(),&senderIP,&senderPort);