工作中想要寫一個工具,但需要知道機器的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();
}