Win11 中 qt 仅需绑定指定接口的本地ip和加入组就可以了
Win10中 需要先设置组播网卡,然后在加入组,入组时还不能再指定接口。具体原因不详
```
setMulticastInterface(lni[nIndex]);
ret = ret?joinMulticastGroup(m_mhost, lni[nIndex]):ret;
```
bool MMultiCast::bindmcast(const char *maddr, int port, const char* ifip)
{
bool ret = false;
QVariant ttl = 10;
QVariant enable = false;
strncpy(m_maddr, maddr, sizeof(m_maddr));
m_mhost = QHostAddress(m_maddr);
m_port = port;
const QList<QNetworkInterface> &lni = QNetworkInterface::allInterfaces();
// ret = bind(QHostAddress::AnyIPv4, port, ShareAddress|ReuseAddressHint);
ret = bind(ifip?QHostAddress(ifip):QHostAddress::AnyIPv4, port, ShareAddress|ReuseAddressHint);
int nIndex = -1;
if (QSysInfo::kernelVersion().startsWith("10.0.2")) {
ret = joinMulticastGroup(m_mhost);
} else {
for (int i = 0; i < lni.size(); i++)
{
qDebug() << "setMulticastInterface"<< i << "name" << lni[i].humanReadableName();
for (auto addr : lni[i].addressEntries())
{
if (addr.ip().toString().compare(ifip) == 0) {
if (nIndex == -1) {
nIndex = i;
qDebug() << "setMulticastInterface nIndex" << nIndex << ifip;
}
qDebug() << "same ip " << nIndex << ifip;
}
}
}
}
if (nIndex >= 0) {
setMulticastInterface(lni[nIndex]);
ret = ret?joinMulticastGroup(m_mhost, lni[nIndex]):ret;
}
if (!ret) {
qDebug() << "join group " << maddr << " failed!!! bind local ip " << ifip;
return false;
}
qDebug() << "bind " << ifip << ret << localAddress();
setSocketOption(MulticastTtlOption, ttl);
setSocketOption(MulticastLoopbackOption, enable);
connect(this, &QUdpSocket::readyRead, this, &MMultiCast::onReadReady);
return ret;
}