Windows下获取本地IP地址的两种方法

  • Post author:
  • Post category:其他


总结两种获取本地IP地址的方法



第一种:C++代码


CmdExe.h

class CmdExc
{
public:
    CmdExc(std::string cmd, std::string mode = "rt");
    ~CmdExc();

    std::string getOutput() const;
    std::string getLocalIP(std::string ipconfig_content);
private:
    std::string m_strOutput__;
    FILE* m_fp__;
};


CmdExe.cpp

CmdExc::CmdExc(std::string cmd, std::string mode)
{
    m_fp__ = _popen(cmd.c_str(), mode.c_str());
    char buf[256] = { 0 };
    if (NULL != m_fp__) {
        int read_len;
        while ((read_len = fread(buf, sizeof(buf) - 1, 1, m_fp__)) > 0) {
            m_strOutput__ += buf;
            memset(buf, 0, sizeof(buf));
        }
    }

}

CmdExc::~CmdExc()
{
    if (NULL != m_fp__) {
        _pclose(m_fp__);
    }
}

std::string CmdExc::getOutput() const
{
    return m_strOutput__;
}

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 CmdExc::getLocalIP(std::string strIpconfig_content)
{
    std::string ip("127.0.0.1");
    auto p = strIpconfig_content.find("IPv4");//查找字符串中第1个出现的"IPv4"
    if (p != std::string::npos)
    {
        auto p2 = strIpconfig_content.find(":", p);
        if (p2 != std::string::npos)
        {
            auto p3 = strIpconfig_content.find("\n", p2);
            if (p3 != std::string::npos)
            {
                ip = strIpconfig_content.substr(p2 + 1, p3 - p2 - 1);
                trimstring(ip);
            }
        }
    }
    
    return ip;
}



第二种:QT代码

#include <Qprocess>

QString getLocalIP()
{
    QString strIpAddress{"127.0.0.1"};
    QProcess cmd_pro;
    QString cmd_str = QString("ipconfig");
    cmd_pro.start("cmd.exe", QStringList() << "/c" << cmd_str);
    cmd_pro.waitForStarted();
    cmd_pro.waitForFinished();
    QString result = cmd_pro.readAll();
    QString pattern("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
    QRegExp rx(pattern);

    int pos = 0;
    bool found = false;
    while ((pos = rx.indexIn(result, pos)) != -1) 
    {
        QString tmp = rx.cap(0);
        //跳过子网掩码 eg:255.255.255.0
        if (-1 == tmp.indexOf("255")) {
            if (strIpAddress != "" && -1 != tmp.indexOf(strIpAddress.mid(0, strIpAddress.lastIndexOf(".")))) {
                found = true;
                break;
            }
            strIpAddress = tmp;
        }
        pos += rx.matchedLength();
    }

    return strIpAddress;
}
int main()
{
	//第一种
    CmdExc cmd("ipconfig");
    std::string strIpconfig_content = cmd.getOutput().c_str();
	std::string strIP = cmd.getLocalIP(strIpconfig_content);
	
	//第二种
	//QString strIP = getLocalIP();
      
    return 0;
}



版权声明:本文为weixin_42326676原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。