代码连接内网共享磁盘WNetCancelConnection();WNetAddConnection2()

7 篇文章 0 订阅

前言

如果你能看到本篇博客说明你应该是对网络磁盘映射有所了解的,如果你不了解网络磁盘映射而是通过PathFileExists();WNetCancelConnection();WNetAddConnection2()这三个函数找到本博客的,可以点击链接了解下网络磁盘映射

https://baike.baidu.com/item/%E6%98%A0%E5%B0%84%E7%BD%91%E7%BB%9C%E9%A9%B1%E5%8A%A8%E5%99%A8/10581942

准备工作

要实现该功能需要用到PathFileExists();WNetCancelConnection();WNetAddConnection2()这三个函数

WNetCancelConnection();WNetAddConnection2()这两个函数需要包含头文件#include <WinNetWk.h>且需要引入库

#pragma comment(lib, "shlwapi.lib")不然编译时会出现如下错误:

error LNK2019: 无法解析的外部符号 __imp__PathRemoveFileSpecA@4,该符号在函数 "void __cdecl WriteLogFile(char const *)" (?WriteLogFile@@YAXPBD@Z) 中被引用

error LNK2019: 无法解析的外部符号 __imp__PathFileExistsA@4,该符号在函数 "void __cdecl Text_PathFileExists(void)" (?Text_PathFileExists@@YAXXZ) 中被引用

函数介绍

如此前置头文件跟库都已经准备好了,下面到三个函数(如果不是很想具体了解函数,就想直接运用的可以跳过这一段,直接去看代码)

PathFileExists()

看一下MSDN的解释:Determines whether a path to a file system object such as a file or directory is valid

翻译过来就是:确定一个文件系统对象的路径,例如文件或目录是否有效

Syntax

BOOL PathFileExists(      
    LPCTSTR pszPath
);

Parameters

pszPath

[in] A pointer to a null-terminated string of maximum length MAX_PATH that contains the full path of the object to verify.

一个指向空终止的最长长度maxpath字符串的指针,该字符串包含要验证的对象的完整路径

Return Value

Returns TRUE if the file exists, or FALSE otherwise. Call GetLastError for extended error information.
如果文件存在,则返回TRUE;否则返回FALSE。调用GetLastError来扩展错误信息

Remarks

This function tests the validity of the path.

A path specified by Universal Naming Convention (UNC) is limited to a file only; that is, \\server\share\file is permitted. A UNC path to a server or server share is not permitted; that is, \\server or \\server\share. This function returns FALSE if a mounted remote drive is out of service.

这个函数测试路径的有效性。
由通用命名约定(UNC)指定的路径仅限一个文件;也就是说,允许服务器共享文件。不允许向服务器或服务器共享的UNC路径;也就是说,服务器或服务器共享。如果挂载的远程驱动器停止服务,该函数返回FALSE。

这是MSDN对该函数的介绍,其实该函数使用起来很简单,例:

PathFileExistsA("Z:");该语句就可以测试你的电脑当前是否存在"Z:"盘这个虚拟磁盘 

WNetCancelConnection()

该函数取消现有网络链接,及如果目标磁盘已经连接上了网络中共享的文件夹,这个函数会让其断开链接

MSDN中原话:The WNetCancelConnection function cancels an existing network connection

翻译过来是:WNetCancelConnection函数取消现有的网络连接

Syntax

DWORD WNetCancelConnection(
  __in  LPCTSTR lpName,
  __in  BOOL fForce
);

Parameters

lpName

Pointer to a constant null-terminated string that specifies the name of either the redirected local device or the remote network resource to disconnect from.

When this parameter specifies a redirected local device, the function cancels only the specified device redirection. If the parameter specifies a remote network resource, only the connections to remote networks without devices are canceled.

指针指向一个常量终止的字符串,它指定重定向本地设备的名称或断开连接的远程网络资源的名称。
当该参数指定重定向的本地设备时,该函数仅取消指定的设备重定向。如果参数指定了远程网络资源,那么只有与没有设备的远程网络的连接被取消

fForce

Specifies whether or not the disconnection should occur if there are open files or jobs on the connection. If this parameter is FALSE, the function fails if there are open files or jobs.

指定如果连接上有打开的文件或作业,是否应该发生断开。如果这个参数是假的,如果有打开的文件或作业,函数就会失败

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is a system error code, such as one of the following values.

如果函数成功,返回值是noerror。
如果函数失败,返回值就是一个系统错误代码,例如下列值之一

Return codeDescription

ERROR_BAD_PROFILE

The user profile is in an incorrect format.

用户配置文件的格式不正确

ERROR_CANNOT_OPEN_PROFILE

The system is unable to open the user profile to process persistent connections.

系统无法打开用户配置文件来处理持久连接

ERROR_DEVICE_IN_USE

The device is in use by an active process and cannot be disconnected.

该设备处于活动过程中,不能断开连接

ERROR_EXTENDED_ERROR

A network-specific error occurred. To obtain a description of the error, call the WNetGetLastError function.

出现了一个特定于网络的错误。要获得错误的描述,请调用WNetGetLastError函数

ERROR_NOT_CONNECTED

The name specified by the lpName parameter is not a redirected device, or the system is not currently connected to the device specified by the parameter.

lpName参数指定的名字不是重定向设备,或者系统目前没有连接到参数指定的设备

ERROR_OPEN_FILES

There are open files, and the fForce parameter is FALSE.

有打开的文件,fForce参数是假的

Remarks

Windows Server 2003 and Windows XP:  The WNet functions create and delete network drive letters in the MS-DOS device namespace associated with a logon session because MS-DOS devices are identified by AuthenticationID. (An AuthenticationID is the locally unique identifier, or LUID, associated with a logon session.) This can affect applications that call one of the WNet functions to create a network drive letter under one user logon, but query for existing network drive letters under a different user logon. An example of this situation could be when a user's second logon is created within a logon session, for example, by calling the CreateProcessAsUser function, and the second logon runs an application that calls the GetLogicalDrives function. GetLogicalDrives does not return network drive letters created by a WNet function under the first logon. Note that in the preceding example the first logon session still exists, and the example could apply to any logon session, including a Terminal Services session. For more information, see Defining an MS-DOS Device Name.
Windows Server 2003和Windows XP:WNet功能在与登录会话相关联的MS-DOS设备名称空间中创建和删除网络驱动器字母,因为MS-DOS设备是由AuthenticationID标识的。(AuthenticationID是与登录会话相关联的本地唯一识别码或LUID。)这可能会影响调用WNet函数之一的应用程序,在一个用户登录下创建一个网络驱动器字母,但是在不同的用户登录下查询现有的网络驱动器字母。这种情况的一个例子是,当用户的第二次登录在徽标中创建时

 该函数使用也不难:WNetCancelConnection(_T("Z:"),FALSE);  //取消了Z:现有的网络连接

 WNetAddConnection2()

MSDN原话:The WNetAddConnection2 function makes a connection to a network resource. The function can redirect a local device to the network resource

翻译过来是:WNetAddConnection2函数连接到网络资源。该函数可以将本地设备重定向到网络资源

补充:WNetAddConnection2函数取代了WNetAddConnection函数。如果您可以将网络资源的提供者用作对话框的所有者窗口,那么可以将其传递给窗口,从而调用WNetAddConnection3函数

Syntax

DWORD WNetAddConnection2(
  __in  LPNETRESOURCE lpNetResource,
  __in  LPCTSTR lpPassword,
  __in  LPCTSTR lpUsername,
  __in  DWORD dwFlags
);

Parameters

lpNetResource

A pointer to a NETRESOURCE structure that specifies details of the proposed connection, such as information about the network resource, the local device, and the network resource provider.

You must specify the following members of the NETRESOURCE structure.

一个指向NETRESOURCE结构的指针,它指定了拟议连接的详细信息,例如关于网络资源、本地设备和网络资源提供者的信息。

//该结构体可以列举出网络邻居信息
//typedef struct  _NETRESOURCEA {
//	DWORD    dwScope; //枚举成员的范围 1枚举当前连接的资源 2枚举网络上的所有资源 3枚举(持久)连接
//	DWORD    dwType;  //资源的类型  1所有资源 2磁盘资源 3 打印资源
//	DWORD    dwDisplayType;  //网络对象显示选项 显示为域、服务器、共享、文件、组、网络、网络的逻辑根、adminstrshare共享、目录、树、Netware目录服务容器
//	DWORD    dwUsage;  //描述如何使用资源的一组位标志 1资源是可连接的资源 2资源是一个容器资源 3资源不是本地设备 4资源是兄弟姐妹 5必须附加资源
//	LPSTR    lpLocalName; //它指定了本地设备的名称。如果连接不使用设备,该成员为NULL。
//	LPSTR    lpRemoteName; //网络名称  
//	LPSTR    lpComment ; //该字符串包含由网络提供程序提供的注释。
//	LPSTR    lpProvider; //该字符串包含拥有该资源的提供者的名称。如果提供者名称未知,该成员可以为NULL
//}NETRESOURCEA, *LPNETRESOURCEA;


您必须指定NETRESOURCE结构的下列成员。

MemberMeaning

dwType

The type of network resource to connect to.

If the lpLocalName member points to a nonempty string, this member can be equal to RESOURCETYPE_DISK or RESOURCETYPE_PRINT.

If lpLocalName is NULL, or if it points to an empty string, dwType can be equal to RESOURCETYPE_DISK, RESOURCETYPE_PRINT, or RESOURCETYPE_ANY.

Although this member is required, its information may be ignored by the network service provider.

连接到的网络资源的类型。
如果lpLocalName成员指向非空字符串,则该成员可以等于resources pedisk或resources peprint。
如果lpLocalName为NULL,或者如果它指向空字符串,dwType就可以等于resources pedisk、resources peprint或resources peany。
尽管这个成员是必需的,但是它的信息可能会被网络服务提供者忽略。

lpLocalName

A pointer to a null-terminated string that specifies the name of a local device to redirect, such as "F:" or "LPT1". The string is treated in a case-insensitive manner.

If the string is empty, or if lpLocalName is NULL, the function makes a connection to the network resource without redirecting a local device.

一个指向一个空终止字符串的指针,它指定要重定向的本地设备的名称,如“F:”或“LPT1”。字符串以不区分大小写的方式处理。
如果弦是空的,或者如果lpLocalName是NULL,那么该函数就会在不重定向本地设备的情况下连接到网络资源。

lpRemoteName

A pointer to a null-terminated string that specifies the network resource to connect to. The string can be up to MAX_PATH characters in length, and must follow the network provider's naming conventions.

一个指向一个空终止字符串的指针,它指定连接到的网络资源。该字符串可以长到maxpath字符,并且必须遵循网络提供者的命名约定。

lpProvider

A pointer to a null-terminated string that specifies the network provider to connect to.

If lpProvider is NULL, or if it points to an empty string, the operating system attempts to determine the correct provider by parsing the string pointed to by the lpRemoteName member.

If this member is not NULL, the operating system attempts to make a connection only to the named network provider.

You should set this member only if you know the network provider you want to use. Otherwise, let the operating system determine which provider the network name maps to.

一个指向一个空终止字符串的指针,它指定连接到的网络提供者。
如果lpProvider是NULL,或者如果它指向一个空字符串,操作系统将尝试通过解析lpRemoteName成员指向的字符串来确定正确的提供者。
如果该成员不是空的,操作系统将尝试只与具名网络提供者建立连接。
如果您知道您想要使用的网络提供者,您应该只设置这个成员。否则,让操作系统决定网络名称映射到哪个提供者。

lpPassword

A pointer to a constant null-terminated string that specifies a password to be used in making the network connection.

If lpPassword is NULL, the function uses the current default password associated with the user specified by the lpUserName parameter.

If lpPassword points to an empty string, the function does not use a password.

If the connection fails because of an invalid password and the CONNECT_INTERACTIVE value is set in the dwFlags parameter, the function displays a dialog box asking the user to type the password.

Windows Me/98/95:  This parameter must be NULL or an empty string.

一个指向一个恒定的空终止字符串的指针,该字符串指定用于建立网络连接的密码。
如果lpPassword是空的,该函数使用与lpUserName参数指定的用户相关联的当前缺省密码。
如果lpPassword指向一个空字符串,则该函数不使用密码。
如果由于无效密码而导致连接失败,并且在dwFlags参数中设置了connectinteractive值,则该函数将显示一个对话框,要求用户输入密码。
Windows me/98/95:该参数必须为NULL或空字符串。 

lpUsername

A pointer to a constant null-terminated string that specifies a user name for making the connection.

If lpUserName is NULL, the function uses the default user name. (The user context for the process provides the default user name.)

The lpUserName parameter is specified when users want to connect to a network resource for which they have been assigned a user name or account other than the default user name or account.

The user-name string represents a security context. It may be specific to a network provider.

Windows Me/98/95:  This parameter must be NULL or an empty string.

一个指向一个永久的空终止字符串的指针,它指定了一个用户名来进行连接。
如果lpUserName为NULL,则该函数使用缺省用户名。(该流程的用户上下文提供缺省用户名。)
当用户想要连接到一个网络资源时,lpUserName参数是指定的,因为他们被分配了一个用户名或帐户,而不是默认的用户名或帐户。
用户名字符串表示安全上下文。它可能是特定于网络提供者的。
Windows me/98/95:该参数必须为NULL或空字符串。 

dwFlags

A set of connection options. The following values are currently defined.

一组连接选项。下面的值是当前定义的

ValueMeaning

CONNECT_INTERACTIVE

If this flag is set, the operating system may interact with the user for authentication purposes.

CONNECT_PROMPT

This flag instructs the system not to use any default settings for user names or passwords without offering the user the opportunity to supply an alternative. This flag is ignored unless CONNECT_INTERACTIVE is also set.

CONNECT_REDIRECT

This flag forces the redirection of a local device when making the connection.

If the lpLocalName member of NETRESOURCE specifies a local device to redirect, this flag has no effect, because the operating system still attempts to redirect the specified device. When the operating system automatically chooses a local device, the dwType member must not be equal to RESOURCETYPE_ANY.

If this flag is not set, a local device is automatically chosen for redirection only if the network requires a local device to be redirected.

Windows Server 2003 and Windows XP:  When the system automatically assigns network drive letters, letters are assigned beginning with Z:, then Y:, and ending with C:. This reduces collision between per-logon drive letters (such as network drive letters) and global drive letters (such as disk drives). Note that earlier versions of Windows assigned drive letters beginning with C: and ending with Z:.

CONNECT_UPDATE_PROFILE

The network resource connection should be remembered.

If this bit flag is set, the operating system automatically attempts to restore the connection when the user logs on.

The operating system remembers only successful connections that redirect local devices. It does not remember connections that are unsuccessful or deviceless connections. (A deviceless connection occurs when the lpLocalName member is NULL or points to an empty string.)

If this bit flag is clear, the operating system does not automatically restore the connection at logon.

CONNECT_COMMANDLINE

If this flag is set, the operating system prompts the user for authentication using the command line instead of a graphical user interface (GUI). This flag is ignored unless CONNECT_INTERACTIVE is also set.

Windows 2000/NT and Windows Me/98/95:  This value is not supported.

CONNECT_CMD_SAVECRED

If this flag is set, and the operating system prompts for a credential, the credential should be saved by the credential manager. If the credential manager is disabled for the caller's logon session, or if the network provider does not support saving credentials, this flag is ignored. This flag is also ignored unless you set the CONNECT_COMMANDLINE flag.

Windows 2000/NT and Windows Me/98/95:  This value is not supported.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is a system error code, such as one of the following values.

如果函数成功,返回值是noerror。
如果函数失败,退货值是一个系统错误代码,比如下列值之一

Return codeDescription

ERROR_ACCESS_DENIED

The caller does not have access to the network resource.

ERROR_ALREADY_ASSIGNED

The local device specified by the lpLocalName member is already connected to a network resource.

ERROR_BAD_DEV_TYPE

The type of local device and the type of network resource do not match.

ERROR_BAD_DEVICE

The value specified by lpLocalName is invalid.

ERROR_BAD_NET_NAME

The value specified by the lpRemoteName member is not acceptable to any network resource provider, either because the resource name is invalid, or because the named resource cannot be located.

ERROR_BAD_PROFILE

The user profile is in an incorrect format.

ERROR_BAD_PROVIDER

The value specified by the lpProvider member does not match any provider.

ERROR_BUSY

The router or provider is busy, possibly initializing. The caller should retry.

ERROR_CANCELLED

The attempt to make the connection was canceled by the user through a dialog box from one of the network resource providers, or by a called resource.

ERROR_CANNOT_OPEN_PROFILE

The system is unable to open the user profile to process persistent connections.

ERROR_DEVICE_ALREADY_REMEMBERED

An entry for the device specified by lpLocalName is already in the user profile.

ERROR_EXTENDED_ERROR

A network-specific error occurred. Call the WNetGetLastError function to obtain a description of the error.

ERROR_INVALID_PASSWORD

The specified password is invalid and the CONNECT_INTERACTIVE flag is not set.

ERROR_NO_NET_OR_BAD_PATH

The operation cannot be performed because a network component is not started or because a specified name cannot be used.

ERROR_NO_NETWORK

The network is unavailable.

这个函数看着很复杂,其实实际应用起来也不算很难,当然了,我这边只应用到该函数连接网络共享磁盘的功能

//设置结构体
NETRESOURCE res = {0};
res.dwType = RESOURCETYPE_DISK;
res.lpLocalName = _T("Z:") ;
//res.lpRemoteName = (LPWSTR)szsharepath;
res.lpRemoteName = _T("\\\\192.168.6.75\\VirtualMachine");
res.lpProvider = NULL;

WNetCancelConnection(_T("Z:"),FALSE);//取消了Z:现有的网络连接
DWORD dwRet = WNetAddConnection2(&res,_T("tht124254"),_T("bwda"),CONNECT_REDIRECT); 

代码

#include <Windows.h>
#include <iostream>
#include <string>
#include <Shlwapi.h> 
#include <time.h>
#include <fstream> 
#include <process.h>
#include <tchar.h>
#include <WinNetWk.h>


using namespace std;
#pragma comment(lib,"Mpr.lib")
#pragma comment(lib, "shlwapi.lib")

void ConnectRemoteDisk()  //连接远程磁盘
{
	while(TRUE)
	{
		if(!PathFileExistsA("Z:"))
		{
			printf("本地不存在该共享磁盘\n");
			//开始远程连接共享磁盘
            DWORD dwusername = 255;
			char szusername[256] = {0};
			GetUserNameA(szusername,&dwusername);
			printf("%s\n",szusername);

			char szsharepath[256] = "\\\\192.168.6.75\\VirtualMachine"; 
            printf("%s\n",szsharepath);
			//strcat(szsharepath,szusername);
			//printf("%s\n",szsharepath);

			//设置结构体
			NETRESOURCE res = {0};
			res.dwType = RESOURCETYPE_DISK; 
			res.lpLocalName = _T("Z:") ;
			//res.lpRemoteName = (LPWSTR)szsharepath;
			res.lpRemoteName = _T("\\\\192.168.6.75\\VirtualMachine");
			res.lpProvider = NULL;

			WNetCancelConnection(_T("Z:"),FALSE);//取消了Z:现有的网络连接
		    DWORD dwRet = 
            WNetAddConnection2(&res,_T("tht124254"),_T("bwda"),CONNECT_REDIRECT); 
            if (NO_ERROR != dwRet)//(4)连接失败
			{
				printf("连接失败\n");
				printf("%d",GetLastError());
               // WriteLogFile("远程连接磁盘失败\n");
			}
			else
			{
				printf("连接成功\n");
               // WriteLogFile("远程连接磁盘成功\n");
			}
			break;
		}
		else
		{
			printf("本地存在该共享磁盘\n");
			break;
		}
	}
}

int main()
{
    //const char * szlog = "连接远程磁盘测试";
   // WriteLogFile(szlog);
    //Get_SetLastError();   //测试setlasterror跟getlasterror两个函数
    //int Tres = Text_MUTEX();  //测试createmutex 创建互斥体函数
    // Text_threadex();    //测试_beginthreadex函数跟_endthreadex函数
	//Text_PathFileExists(); //测试盘符是否存在
    ConnectRemoteDisk();  //连接远程磁盘

    system("pause");

	return 0;
}

补充

一般而言想要连接一个内网共享文件夹需要ip地址及文件夹名字

类似下面格式

当你确定后会让你输入登录的账号跟密码

代码中res.lpRemoteName = _T("\\\\192.168.6.75\\VirtualMachine");这句是在结构体 NETRESOURCEA中设置连接的网络信息

WNetAddConnection2(&res,_T("tht124254"),_T("bwda"),CONNECT_REDIRECT);这函数的参数设置的用户名_T("bwda")跟密码_T("tht124254")

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值