«

在 windows 下调用 _popen 函数来获取内网 ip 地址

时间:2022-2-6 21:54     作者:独元殇     分类: C/C++


这个程序不是跨平台的,因为 _popen 是 windows 下的,它不是标准库函数,但 linux 下也有类似的,就叫 popen 。另外, ipconfig 也是 windows 独有的。在 linux 下有一个 ifconfig 。

#include <iostream>
#include <string>

void trimstring(std::string& str)
{
    if (!str.empty())
    {
        str.erase(0, str.find_first_not_of(" "));
        str.erase(str.find_last_not_of(" ") + 1);
    }
}

std::string getlocalip()
{
    std::string ip("127.0.0.1");
    std::string ipconfig_content;

    FILE* fp = _popen("ipconfig", "r");
    if (NULL != fp)
    {
        char line[4096];
        while (NULL != fgets(line, sizeof(line), fp))
        {
            ipconfig_content += line;
        }

        auto p = ipconfig_content.rfind("IPv4");
        if (p != std::string::npos)
        {
            auto p2 = ipconfig_content.find(":", p);
            if (p2 != std::string::npos)
            {
                auto p3 = ipconfig_content.find("\n", p2);
                if (p3 != std::string::npos)
                {
                    ip = ipconfig_content.substr(p2 + 1, p3 - p2 - 1);
                    trimstring(ip);
                }
            }
        }

        _pclose(fp);
    }

    return ip;
}

int main()
{
    std::cout << getlocalip() << std::endl;

    std::cin.get();
}

标签: 原创 Windows

推荐阅读: