获取LAN IP地址不起作用

时间:2016-05-13 15:09:04

标签: c++ winapi ip lan

代码如下。我想列举所有的ips。部分代码用于我的GUI,我确信错误与它们无关。

void udpchat1::getNameAndIp() {

    struct   hostent   *host;
    struct   in_addr   *ptr;

    DWORD   dwScope = RESOURCE_CONTEXT;
    NETRESOURCE   *NetResource = NULL;
    HANDLE   hEnum;
    WNetOpenEnum(dwScope, NULL, NULL, NULL, &hEnum);

    WSADATA   wsaData;
    WSAStartup(MAKEWORD(1, 1), &wsaData);
    ui.IpListWidget->clear();
    names.clear();
    ui.chatIpLabel->setText("1111111111111");
    sendAble = false;
    //  flag = false;

    if (hEnum)
    {
        DWORD   Count = 0xFFFFFFFF;
        DWORD   BufferSize = 10240;
        LPVOID   Buffer = new char[10240];
        WNetEnumResource(hEnum, &Count, Buffer, &BufferSize);
        NetResource = (NETRESOURCE*)Buffer;

        char szHostName[200];

        for (unsigned int i = 0; i < BufferSize / sizeof(NETRESOURCE); i++, NetResource++)
        {
            if (NetResource->dwUsage == RESOURCEUSAGE_CONTAINER && NetResource->dwType == RESOURCETYPE_ANY)
            {
                if (NetResource->lpRemoteName)
                {
                    CString   strFullName = NetResource->lpRemoteName;
                    if (0 == strFullName.Left(2).Compare(_T("\\\\")))
                        strFullName = strFullName.Right(strFullName.GetLength() - 2);

                    gethostname(szHostName, strlen(szHostName));
                    USES_CONVERSION;
                    char *pchar = T2A(strFullName);
                    host = gethostbyname(pchar);

                    if (host == NULL)   continue;
                    ptr = (struct in_addr *)   host->h_addr_list[0];

                    std::string str = "";
                    for (int n = 0; n < 4; n++)
                    {
                        CString addr;
                        if (n > 0)
                        {
                            str += ".";
                        }
                        int value = (unsigned int)((unsigned char*)host->h_addr_list[0])[n];
                        char p[20];
                        sprintf(p, "%d", value);
                        str.append(p);
                    }
                    names.insert(std::pair<std::string, std::string>(host->h_name, str));
                    ui.IpListWidget->addItem(QString::fromStdString(host->h_name));
                    //std::cout << "IP:" << str << " Name:" << host->h_name << std::endl;
                }
            }
        }
        delete   Buffer;
        WNetCloseEnum(hEnum);
    }
    WSACleanup();

}

我使用了调试,我发现程序无法进入此if语句。

if (NetResource->lpRemoteName)

以下是调试检查器的屏幕截图。

image

0 个答案:

没有答案