您的位置:首页 > 理论基础

C++:gethostname,gethostbyname获取IP地址和计算机名

2017-03-24 09:57 441 查看
使用gethostname()和gethostbyname()获取IP地址和计算机名,记录一下,省得老忘。

[cpp] view plain copy

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;

}

[cpp] view plain copy

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: