扫描网络邻居内的所有IP和用户名的步骤
如何扫描网络邻居内的所有IP和用户名
#include "Winsock2.h"
#include "afxtempl.h"
#include "Winnetwk.h"
加入lib链接Project-》setting-》link-》object/libary modules 中
加入Ws2_32.lib Mpr.lib
CList<CString,CString&> m_list;
m_list.RemoveAll();
CString strTemp;
struct hostent *host;
struct in_addr *ptr;// 获得IP地址
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 = 2048;
LPVOID Buffer = new char[2048];
// 调用WSAStartup后调用WNetEnumResource做进一步的枚举工作
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("////") )strFullName = strFullName.Right(strFullName.GetLength()-2);
//获得主机名
gethostname( szHostName, strlen( szHostName ) );
//由主机名获得跟它对应的主机信息
host = gethostbyname(strFullName);
if(host == NULL) continue;
ptr = (struct in_addr *) host->h_addr_list[0];
// 提取IP地址信息,地址形式如下: 211.40.35.76
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
strTemp.Format("%s --> %d.%d.%d.%d",strFullName,a,b,c,d);
// 加入到链表中
m_list.AddTail(strTemp);
}
}
}
delete Buffer;
// 结束枚举工作
WNetCloseEnum( hEnum );
}
// 卸载Winsock.dll
WSACleanup();
列出本机IP地址和名字
CString m_strIPAddress;
WSADATA wsaData;
int iRet = WSAStartup(MAKEWORD(0x02, 0x02), &wsaData);
if (iRet != 0)
{
TRACE("初始化winsock动态库出错!");
m_strIPAddress = "";
return;
}
struct in_addr localaddr;
struct hostent *hp=NULL;
char hostname[50];
gethostname(hostname,49);//主机名
hp=gethostbyname(hostname);//主机信息
memcpy(&localaddr,hp->h_addr,hp->h_length);//地址
m_strIPAddress = inet_ntoa(localaddr);//变成char *
WSACleanup();
本文地址:http://www.45fan.com/dnjc/67732.html