qt中判断当前电脑中是否包含某一ip地址

bool winUdp::GetLocalIp(char *szIP)// 获取IP
{
    char szHostName[128];
    ZeroMemory(szHostName, sizeof(szHostName));
    if (gethostname(szHostName, sizeof(szHostName))== 0)//gethostname 函数要在WSAStartup后进行调用。。。
    {
        HOSTENT*pHostEnt = gethostbyname(szHostName);
        qDebug() << "szHostName = " <<szHostName<<szIP<<pHostEnt->h_length<< endl;//pHostEnt->h_length表示当前ip的个数,比如有的电脑有几个网卡或者一个网卡有几个ip地址
        if (pHostEnt)
        {
            string s2;
            bool okIP=false;
            for(int i=0;i<pHostEnt->h_length;i++)
            {
                char tmpIP[20];
                sprintf(tmpIP, "%d.%d.%d.%d", (pHostEnt->h_addr_list[i][0] & 0xff),
                        (pHostEnt->h_addr_list[i][1] & 0xff),
                        (pHostEnt->h_addr_list[i][2] & 0xff),
                        (pHostEnt->h_addr_list[i][3] & 0xff));
                s2=tmpIP;
                if(s2.compare(szIP)==0)
                    okIP=true;
                printf("\n%d,%s,%s\n",i,tmpIP,s2.c_str());;
            }
            return okIP;
        }
    }
    else
    {
        qDebug()<< "gethostname error code:" << WSAGetLastError()<<endl;
        return false;
    }
    return true;
}

在qt中进行udp通信时,需要先判别电脑是否包含某一ip地址,通过上述函数实现.判别当前配置中是否包含szIP中所描述的地址,包含返回true,否则范围false

posted @ 2022-08-16 18:02  Seeyou123  阅读(178)  评论(0编辑  收藏  举报