连上局域网某一台主机,并在该台机中创建一个共享文件夹 C++ 代码实现
时间: 2024-03-11 22:50:26 浏览: 76
以下是在 Windows 操作系统下,使用 C++ 实现连接局域网中的一台主机并创建共享文件夹的代码:
```c++
#include <iostream>
#include <windows.h>
#include <lm.h>
#pragma comment(lib, "netapi32.lib")
int main() {
// 填写共享文件夹的名称和路径
std::wstring shareName = L"MySharedFolder";
std::wstring sharePath = L"C:\\MyFolder";
// 填写远程主机名和用户名、密码(如果需要认证)
std::wstring remoteHost = L"192.168.1.100";
std::wstring remoteUser = L"Administrator";
std::wstring remotePass = L"password";
// 连接远程主机
NETRESOURCE netResource;
netResource.dwType = RESOURCETYPE_DISK;
netResource.lpLocalName = NULL;
netResource.lpRemoteName = const_cast<wchar_t*>(remoteHost.c_str());
netResource.lpProvider = NULL;
DWORD res = WNetAddConnection2(&netResource, remotePass.c_str(), remoteUser.c_str(), 0);
if (res != NO_ERROR) {
std::wcerr << L"Failed to connect to remote host: " << res << std::endl;
return 1;
}
// 创建共享文件夹
SHARE_INFO_2 shareInfo;
shareInfo.shi2_netname = const_cast<wchar_t*>(shareName.c_str());
shareInfo.shi2_type = STYPE_DISKTREE;
shareInfo.shi2_remark = NULL;
shareInfo.shi2_permissions = ACCESS_ALL;
shareInfo.shi2_max_uses = -1;
shareInfo.shi2_current_uses = 0;
shareInfo.shi2_path = const_cast<wchar_t*>(sharePath.c_str());
shareInfo.shi2_passwd = NULL;
res = NetShareAdd(NULL, 2, reinterpret_cast<LPBYTE>(&shareInfo), NULL);
if (res != NERR_Success) {
std::wcerr << L"Failed to create share: " << res << std::endl;
}
// 断开连接
WNetCancelConnection2(remoteHost.c_str(), 0, TRUE);
return 0;
}
```
这段代码使用了 Windows API 中的 WNetAddConnection2 和 NetShareAdd 函数,其中 WNetAddConnection2 用于连接远程主机,NetShareAdd 用于创建共享文件夹。注意在代码中填写正确的远程主机名、用户名和密码。
阅读全文