前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在 windows 下调用 _popen 函数来获取内网 ip 地址

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

作者头像
独元殇
发布2023-03-16 11:02:33
1.3K0
发布2023-03-16 11:02:33
举报
文章被收录于专栏:独元殇的文章独元殇的文章

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

代码语言:javascript
复制
#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();
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-2-6 21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档