编译运行环境:
集成开发环境:Microsoft Visual Studio 2019
代码运行环境:windows 10专业版 ,64位操作系统
代码
下述是可以直接使用的代码。
- 头文件
#include <windows.h>
#include <winsock.h>
#include <string>
#pragma comment(lib,"wsock32.lib")
- 实现函数
std::string CheckIP()
{
WSADATA wsaData;
char name[255];
char* ip;
PHOSTENT hostinfo;
std::string ipStr;
if(WSAStartup(MAKEWORD(2,0),&wsaData) == 0)
{
if(gethostname(name, sizeof(name)) == 0)
{
if((hostinfo = gethostbuname(name)) != NULL)
{
ip = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
ipStr = ip;
}
}
WSACleanup();
}
return ipStr;
}
- 调用
int _tmain(int argc, _TCHAR* argv[])
{
printf("my IP is %s",CheckIP().c_str());
system("pause");
}