CString CDataSocket::GetLocalHostName() //获得本地计算机名称
{
char szHostName[256];
if(gethostname(szHostName,sizeof(szHostName))!=0)
return CString("");
else
return CString(szHostName);
}
CString CDataSocket::GetIPAddress()//获得本地IP
{
hostent* lpHostEnt;
char szHostName[256];
LPSTR lpAddr;
struct in_addr inAddr;
if(gethostname(szHostName,sizeof(szHostName))!=0)
return CString("");
lpHostEnt=gethostbyname(szHostName);
if(lpHostEnt==NULL)
return CString("");
//获取IP列表,这里我们只关心其中第一个IP地址
lpAddr=lpHostEnt->h_addr_list[0];
if(lpAddr==NULL)
return CString("");
memmove(&inAddr,lpAddr,4);
return CString(inet_ntoa(inAddr));
}
本文介绍了使用C++实现获取本地计算机名称及IP地址的方法。通过gethostname函数获取主机名,并利用gethostbyname函数解析得到IP地址。
169

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



