问题描述
在Win10\Win11下使用addIPAddress添加临时IP成功后,立即创建socket,bind失败
cpp
if(!m_socket->bind(QHostAddress(m_localIP), listenPort))
{
qCritical() << QString("bind error %1").arg(m_socket->errorString());
return;
}
错误输出:
bind error 这个地址不可用
解决方案
经测试addIPAddress添加临时IP后,未立即生效,至少要超过3秒的等待时间,故采用如下方案:
cpp
int count = 0;
bool bindOK = false;
do
{
bindOK = m_socket->bind(QHostAddress(m_localIP), listenPort);
if(bindOK){
break;
}
QThread::msleep(500);
} while (count++ < 12);
if (!bindOK)
{
qCritical() << QString("bind error %1").arg(m_socket->errorString());
return;
}
查询相关资料
https://learn.microsoft.com/zh-cn/windows/win32/api/iphlpapi/nf-iphlpapi-addipaddress
https://bbs.csdn.net/topics/390226048
https://stackoverflow.com/questions/23620805/addipaddress-not-taking-immediate-effect