工控编程吧
标题:
331上位机VC MFC获取局域网计算机名称及IP
[打印本页]
作者:
qq263946146
时间:
2016-9-21 21:14
标题:
331上位机VC MFC获取局域网计算机名称及IP
(, 下载次数: 1)
上传
点击文件名下载附件
获取局域网计算机名称及IP
功能展示
同一局域网,在生产现场会有多台电脑,如何获取全部局域网的电脑名称及IP? 我们当前例程实现这一功能,
效果如图,点击按钮就可将全部局域网的计算机名及IP显示在列表控件中;
要点提示
例程中使用了WINDOWS API函数库中的WNetOpenEnum() WNetEnumResource() WNetCloseEnum()等函数,
在使用这些函数前得添加这些函数所在头文件及导入静态库#include <afxsock.h>
#pragma comment(lib,"mpr.lib")
实现功能
1.新建基于对话框的应用程序
2.依照例程添加按钮<获取局域网全部计算机IP>及列表控件IDC_LIST1,关联按钮的点击函数
#include <afxsock.h>
#pragma comment(lib,"mpr.lib")
void CGkbc8Dlg::OnGet()
{
CListCtrl* pListCtrl=(CListCtrl*)GetDlgItem(IDC_LIST1);
pListCtrl->DeleteAllItems();//清空全部内容
//<>
WSADATA wsd;
WSAStartup(MAKEWORD(2,2),&wsd);
DWORD Count=0xFFFFFFFF,Bufsize=4096,Res;
NETRESOURCE* nRes;
NETRESOURCE* nRes1;
NETRESOURCE* nRes2;
HANDLE lphEnum;
LPVOID Buf = new char[4096];
LPVOID Buf1 = new char[4096];
LPVOID Buf2 = new char[4096];
Res = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER,NULL,&lphEnum);
Res=WNetEnumResource(lphEnum,&Count,Buf,&Bufsize);
nRes=(NETRESOURCE*)Buf;
for(DWORD n=0;n<Count;n++,nRes++)
{
DWORD Count1=0xFFFFFFFF;
Res = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER,nRes,&lphEnum);
Res=WNetEnumResource(lphEnum,&Count1,Buf1,&Bufsize);
nRes1=(NETRESOURCE*)Buf1;
}
for(DWORD i=0;i<Count1;i++,nRes1++)
{
DWORD Count2=0xFFFFFFFF;
Res = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER,nRes1,&lphEnum);
Res=WNetEnumResource(lphEnum,&Count2,Buf2,&Bufsize);
nRes2=(NETRESOURCE*)Buf2;
for(DWORD j=0;j<Count2;j++,nRes2++)
{
pListCtrl->InsertItem(j,0);
CString sName=nRes2->lpRemoteName;
sName=sName.Right(sName.GetLength()-2);
pListCtrl->SetItemText(j,0,sName);
CString str="";
struct hostent * pHost;
pHost = gethostbyname(sName);
if(pHost==NULL)
{
pListCtrl->SetItemText(j,1,"无法获得IP地址");
}
else
{
for(int n=0;n<4;n++)
{
CString addr;
if(n > 0)
{
str += ".";
}
addr.Format("%u",(unsigned int)((unsigned char*)pHost->h_addr_list[0])[n]);
str += addr;
}
pListCtrl->SetItemText(j,1,str);
}
}
}
}
delete Buf; delete Buf1; delete Buf2; WNetCloseEnum(lphEnum);
我们来演示下功能实现的整个过程
[iqiyi]http://player.video.qiyi.com/ba1dd88c91447ea5af7757786132b472/0/0/w_19rstj0wtp.swf-albumId=6347999809-tvId=6347999809-isPurchase=0-cnId=12[/iqiyi]
(, 下载次数: 1)
上传
点击文件名下载附件 [weixinlianxi]1[/weixinlianxi]
[note]1[/note]
欢迎光临 工控编程吧 (https://www.gkbc8.com/)
Powered by Discuz! X3.4