使用VC建立网络连接并访问网络资源

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/charlee44/article/details/88051131

1. 提出问题

在windows下可以通过系统操作,将局域网的资源映射到本地,从而实现像本地数据一样访问网络资源。实际上这些步骤也可通过代码调用win32函数实现,前提是你得知道目标机器的地址以及密钥。

2. 解决方案

直接上VC的实例代码:

#include <Windows.h>
#include <iostream>
#include <fstream>

#pragma comment(lib, "mpr.lib")
#pragma comment(lib, "Netapi32.lib")

using namespace std;

int main()
{
	//在目标机器磁盘建立一个1.txt,无法直接读取
	ifstream infile("\\\\Jishi\\D\\1.txt");
	if (infile)
	{
		cout << "read txt!" << endl;
	}
	else
	{
		cout << "can't read txt!" << endl;
	}
	infile.close();

	//建立网络磁盘映射的连接
	string localName = "Y:";
	string remoteName = "\\\\Jishi\\D";
	string password = "123456";
	string user = "administrator";

	NETRESOURCE nr = { 0 };
	nr.dwType = RESOURCETYPE_ANY;
	nr.lpLocalName = const_cast<char *>(localName.c_str());
	nr.lpRemoteName = const_cast<char *>(remoteName.c_str());
	nr.lpProvider = NULL;

	DWORD dRes = WNetAddConnection2(&nr, password.c_str(), user.c_str(), CONNECT_UPDATE_PROFILE);

	//通过GetLastError()检查错误代码
	cout <<"连接结果:"<< dRes << endl;

	//读取映射盘符的连接
	ifstream infile1("Y:\\1.txt");
	if (infile1)
	{
		cout << "read txt!" << endl;
	}
	else
	{
		cout << "can't read txt!" << endl;
	}
	infile1.close();

	//读取网络地址的连接
	ifstream infile2("\\\\Jishi\\D\\1.txt");
	if (infile2)
	{
		cout << "read txt!" << endl;
	}
	else
	{
		cout << "can't read txt!" << endl;
	}
	infile2.close();

	//最后断开Y盘的连接
	WNetCancelConnection("Y:", TRUE);

    return 0;
}

该功能主要是通过调用WNetAddConnection2()函数来实现连接,通过WNetCancelConnection()函数断开的。其实连接后可以保证一定运行周期都是有效的,不用每次都断开重新再连。实际运用过程中两个函数的返回值会提供错误信息,可以通过GetLastError()获取并检查。
这里访问了三次网络资源,连接前访问,连接后映射地址访问,网络地址访问。这里的网络地址改成IP地址也是可以的。运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/charlee44/article/details/88051131