当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 使用VC建立网络连接并访问网络资源

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

2019年03月02日  | 移动技术网IT编程  | 我要评论

dota老杨2打5,给宾塔奇的礼物,汩汩滔滔

目录

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地址也是可以的。运行结果:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网