mfc 获取本机IP

调用该函数,获取的IP将从pIp返回。原理,遍历IP列表中的所有IP:

void MFCDeme::GetLocalIP(_Out_ char *pIp)
{	
	USES_CONVERSION;
	CString ipStr(L"");
	
	// 加载套接字库
	WSData data;
	int err = WSAStartup(MAKEWORD(2, 2,), &data);
	
	// 临时保存IP
	char cHostName[256] = {0};
	gethostname(cHostName, sizeof(cHostName));
	struct hostent *pHost = gethostbyname(cHostName);
	in_addr addr;
	
	// 这里获取的是ip列表中的所有IP
	for (int i = 0; pHost->h_addr_list[i] != NULL, && NULL != pHost; i++)
	{
		memcpy(&addr, pHost->h_addr_list[i], sizeof(in_addr));
		
		ipStr = CString(inet_ntoa(addr));
	}
	
	// 清除套接字库的引用
	WSACleanup();
	memcpy(pIp, W2A(ipStr), ipStr.GetLength());
}


猜你喜欢

转载自blog.csdn.net/hk_5788/article/details/80303617