獲得區域網內IP地址和主機名
原始碼:
#pragma comment(lib,"Mpr.lib") //否則編譯不能通過
void GetNameAndIp(CStringArray& NameArray,CStringArray& IpArray)
{
NameArray.RemoveAll();
IpArray.RemoveAll();
struct hostent *host;
struct in_addr *ptr;
DWORD dwScope = RESOURCE_CONTEXT;
NETRESOURCE *NetResource = NULL;
HANDLE hEnum;
WNetOpenEnum(dwScope, NULL, NULL, NULL, &hEnum);
WSADATA wsaData;
WSAStartup(MAKEWORD(1,1),&wsaData);
if(hEnum)
{
DWORD Count = 0xFFFFFFFF;
DWORD BufferSize = 10240;
LPVOID Buffer = new char[10240];
WNetEnumResource(hEnum, &Count,Buffer, &BufferSize);
NetResource = (NETRESOURCE*)Buffer;
char szHostName[200];
for( unsigned int i = 0;i < BufferSize/sizeof(NETRESOURCE); i++, NetResource++)
{
if (NetResource->dwUsage == RESOURCEUSAGE_CONTAINER && NetResource->dwType == RESOURCETYPE_ANY )
{
if(NetResource->lpRemoteName)
{
CString strFullName = NetResource->lpRemoteName;
if(0 == strFullName.Left(2).Compare(_T("\\\\")))
strFullName = strFullName.Right(strFullName.GetLength()-2);
gethostname(szHostName,strlen(szHostName));
USES_CONVERSION;
char *pchar = strFullName.GetBuffer();
host = gethostbyname(pchar);
if(host == NULL) continue;
ptr = (struct in_addr *) host->h_addr_list[0];
int a = ptr->S_un.S_un_b.s_b1; // 211
int b = ptr->S_un.S_un_b.s_b2; // 40
int c = ptr->S_un.S_un_b.s_b3; // 35
int d = ptr->S_un.S_un_b.s_b4; // 76
CString strTemp;
strTemp.Format(_T("%d.%d.%d.%d"),a,b,c,d);
NameArray.Add(strFullName);
IpArray.Add(strTemp);
}
}
}
delete Buffer;
WNetCloseEnum(hEnum);
}
WSACleanup();
}
客戶端就可以呼叫GetNameAndIp介面來獲得所有的ip地址和主機名:
CString csName;
CString csIp;
CStringArray m_csNameArray;
CStringArray m_csIpArray;
GetNameAndIp(m_csNameArray,m_csIpArray);
for(int i=0;i<m_csNameArray.GetCount();i++)
{
csName = m_csNameArray.GetAt(i);
csIp = m_csIpArray.GetAt(i);
}
在一個區域網內測試發現,區域網內有的PC沒有找到,調查發現因為這些PC不在同一個工作組。
右擊我的電腦-〉屬性->計算機名 檢視工作組是不是在同一個組內。
早晚喝
---------------------
作者:luliyuan
來源:CSDN
原文:https://blog.csdn.net/luliyuan/article/details/7947457
版權宣告:本文為博主原創文章,轉載請附上博文連結!
這裡還有一個https://blog.csdn.net/foxmail/