源代码:
#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不在同一个工作组。
右击我的电脑-〉属性->计算机名 查看工作组是不是在同一个组内。