windows使用C++获取本机IP地址

工作中想要写一个工具,但需要知道机器的IP地址。查了下,没有发现什么好的接口可以直接获取。

我的机器就一个IP,其他的是虚拟机的。使用 ipconfig 可以列出它们。但我需要知道的就是如同 192.168.10.111 这样的一个字符串,不需要其他的信息。

于是自己写了一个,这个程序不是跨平台的,因为 _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();
}
原文地址:https://www.cnblogs.com/demon90s/p/15587773.html