使用gethostname()和gethostbyname()获取IP地址和计算机名,记录一下,省得老忘。
int CNetTestDlg::GetLocalHostName( CString& sHostName ) // 获取机器名
{
char szHostName[256];
int nRetCode;
nRetCode = gethostname(szHostName, sizeof(szHostName));
if (nRetCode != 0)
{
memcpy(szHostName, ("Not Available"), sizeof("Not Available"));
return WSAGetLastError();
}
sHostName = szHostName;
return 0;
}
int CNetTestDlg::GetIPAddress(const CString& sHostName, CString& sIPAddress) // 获取IP地址
{
struct hostent *lpHostEnt = gethostbyname(sHostName);
if (lpHostEnt == NULL)
{
sIPAddress = "";
return WSAGetLastError();
}
LPSTR lpAddr = lpHostEnt->h_addr;
if (lpAddr)
{
struct in_addr inAddr;
memmove(&inAddr, lpAddr, 4); // 将地址进行转换成常规形式
sIPAddress = inet_ntoa(inAddr);
if (sIPAddress.IsEmpty())
{
sIPAddress = "Not available";
}
}
return 0;
}
本文提供了一段C++代码示例,展示了如何通过gethostname()和gethostbyname()函数获取本地计算机的名称和IP地址,并对获取过程中可能出现的错误进行了处理。

3582

被折叠的 条评论
为什么被折叠?



